<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>实现元素水平居中</title>
<style>
.box{
background-color: skyblue;
margin-bottom: 30px;
}
.text{
width: 200px;
height: 200px;
background-color: pink;
margin: 0 auto;
}
.box2{
text-align: center;
/*display: inline-block;*/
}
.box2 input{
width: 300px;
height: 40px;
}
.box3{
text-align: center;
width: 400px;
display: inline-block;
}
.box4{
height: 200px;
}
.text4{
background-color: lightCoral;
width: 600px;
/*margin: 0 auto;*/
/*position: relative;
top: 10px;
left: 10px;*/
/*position: fixed;*/
position: absolute;
left: 50%;
margin-left: -300px;
}
</style>
</head>
<body>
<div class="box box1">
<div class="text">
<b>方法一:</b><br>
这是一个块级标签,如何居中?(粉色部分)<br><br>
给自己设置:margin: 0 auto;
会根据父级标签居中
</div>
</div>
<b>方法二:</b>输入框是一个行内块级元素,给父级设置text-align: center;可以实现居中,前提:父级元素是块级元素
<div class="box box2">
<input type="text" placeholder="这是输入框,行内块级元素">
</div>
<b>方法三:</b>行级标签居中,给父级标签设置:text-align: center;,父级标签可以块级可以行内块级
<div class="box box3">
<a href="" title="">a标签是一个行级标签,不可设置宽高</a>
</div>
<b>方法四:</b>
<div class="box box4">
<div class="text4">
<b>方法四:</b><br>
这是一个块级标签,并且有绝对定位(absolute),如何居中?(粉色部分),当设置成这两个属性后,父级高度不会被撑开,margin: 0 auto;也会失去作用,如果还想要居中可以采用:left: 50%;
margin-left: -300px;自身宽度的一半
</div>
</div>
</body>
</html>
复制粘贴浏览器查看即可看到效果