元素居中有很多种方法,自己整理一下常用的。
先来最复杂的,水平垂直都居中。
1.flex大法,不论什么型号的元素,以下三句话解决问题。
display:flex;
justify-content:center;
align-items:center;
2.postion定位法
2.1子元素不定宽高
.father3{
position: relative;
background: coral;
width:500px;
height:400px;
}
.son3{
background: cadetblue;
position: absolute;
top: 50%;
left:50%;
transform:translate(-50%,-50%);
}
<div class="father3">
<div class="son3">3233</div>
</div>
父元素得是除static定位元素,子元素才能用absolute,然后相对于父元素移动,top50%是向下移动了父元素的一半,子元素还需要向上移动自身的一半才可以, transform:translate(-50%,-50%)未知子元素宽高,反正就是挪动他自己一半就是了。
2.2子元素定宽高
.father3{
position: relative;
background: coral;
width:500px;
height:400px;
}
.son3{
background: cadetblue;
position: absolute;
width:100px;
height:100px;
top: 50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
<div class="father3">
<div class="son3">3233</div>
</div>
实现效果和2.1方法一样,原理也类似,还需要挪动子元素自身一半来实现。
2.3子元素定宽高
.father4{
position: relative;
background: coral;
width:500px;
height:400px;
}
.son4{
background: cadetblue;
position: absolute;
width:100px;
height:100px;
margin:auto;
top:0;left:0;right:0;bottom:0;
}
<div class="father4">
<div class="son4">3233</div>
</div>
实现效果和上面一样,这个就是利用margin自动分配空间。
3.display:table,父元素设置display:table,子元素设置为单元格display:table-cell,这个方法没用过,不太友好。
水平居中
这个就比较基础,margin:0 auto,想让谁水平居中居中就给他设置。
垂直居中
.father2{
position: relative;
background: coral;
width:500px;
height:400px;
}
.son2{
background: cadetblue;
position: absolute;
top: 50%;
transform:translateY(-50%);
}
<div class="father2">
<span class="son2">3233</span>
</div>
这个就是定位法,设置单个方向的移动,当然也可以变形,为水平居中。
单独对于行内元素来说
<!-- 行内元素水平居中 父元素设置text-align:center; -->
<div style="text-align:center;background: blueviolet;height:100px;">
<span style="background: brown;">1</span>
</div>
<br>
<!-- 行内元素垂直居中 父元素设置line-height等于自身高度-->
<div style="background: blueviolet;height:100px;line-height: 100px;">
<span style="background: brown;">1</span>
<span style="background: brown;">1</span>
<span style="background: brown;">1</span>
</div>
<br>
<!-- 行内元素水平垂直居中 上面两个结合 -->
<div style="text-align:center;background: blueviolet;height:100px;line-height: 100px;">
<span style="background: brown;">1</span>
<span style="background: brown;">1</span>
<span style="background: brown;">1</span>
</div>
<br>