1:行块元素
针对行内元素,例如:span a img text input 水平居中的方法,给父元素 text-align :center;
例如:在这里插入代码片
<div class="parent">
<span>inline element</span>
</div>
行内居中只需要给父元素设置 text-align: center
就可以实现。
.parent {
text-align: center;
width: 200px;
height: 50px;
border: 1px solid red;
}
注意
对于元素中的块级元素它是不起作用的。但是可以把块级元素的 display 设置为 inline-block 或者 inline 之后,也是可以生效的,但是需要注意设置 inline 之后是会丢失一些功能的,比如设置元素的宽高
2:块级元素 设置margin
margin :0 auto,可实现块级元素的水平居中
<div class="chilren"></div>
.chilren {
margin: 0 auto;
width: 20px;
height: 20px;
background: red;
}
3-1.定位: absolute
首先给父元素添加 position: relative 这样子元素就可以通过父元素来实现绝对定位。然后让元素向左边距 负元素宽度的一半,这样就能完美实现居中啦。(这个方法在垂直居中的时候同样适用)
<div class="fater">
<div class="chilren"></div>
</div>
.parent {
position: relative;
width: 200px;
height: 50px;
border: 1px solid red;
}
.chilren {
position: absolute;
left: 50%;
margin-left:-25px;
width: 50px;
height: 50px;
background: red;
}
3-2 :position +transform
首先给父元素添加 position: relative 这样子元素就可以通过父元素来实现绝对定位。然后让元素向右偏移 50%,需要注意,这个时候居中的是子元素的左边线。所以这时候就需要使用 transilateX(-50%) 让元素再相对自己向右位移 50%,这样就能完美实现居中啦。(这个方法在垂直居中的时候同样适用)
<div class="center">
</div>
.center {
height: 400px;
width: 400px;
background-color: pink;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
}
4.flex布局
使用弹性布局也可以很方便的实现水平居中(和垂直居中 align-items: center; )
<div class="father">
<div>a</div>
<div>b</div>
</div>
.father {
height: 400px;
width: 400px;
background-color: skyblue;
margin: 100px;
display: flex;
justify-content: center; //水平居中
align-items: center; //垂直居中
}
.father div {
height: 30px;
width: 30px;
background-color: pink;
}