css垂直居中技巧总结
1、Line-height + inline-block
<div class="box box2">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
border: 1px solid #f00;
margin: auto;
line-height: 200px;
text-align: center;
}
.box2 .content{
display: inline-block;
height: auto;
line-height:1;
width: 400px;
background: #ccc;
}
2、:before + inline-block
唯独需要特别处理掉inline-block元素之间的4-5px空间这个小缺陷,利用font-size:0
<h2>:before + inline-block</h2>
<div class="box box3">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
height: 250px;
border: 1px solid #f00;
margin: auto;
text-align: center;
font-size:0;
}
.box::before{
content:'';
display: inline-block;
height: 100%;
width: 0;
vertical-align: middle;
}
.box .content{
width: 400px;
background: #ccc;
display: inline-block;
vertical-align: middle;
font-size:14px;
}
3、absolute + margin auto
当元素设置为绝对定位后,假设它是抓不到整体可运用的空间范围,所以margin:auto会失效,但当你设置了top:0;bottom:0;时,绝对定位元素就抓到了可运用的空间了,这时你的margin:auto就生效了(神奇吧),如果你的绝对定位元素需要水平居中于父层,那你同样可以设定left:0;right:0;来让绝对定位元素取得空间可运用范围,再让marign-left与margin-right设定为auto即可居中。但此方式的缺点是你的定位元素必须有固定的宽高(百分比也算)才能正常居中。
<h2>absolute + translate(-50%, -50%)</h2>
<div class="box box5">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
height: 250px;
border: 1px solid #f00;
margin: auto;
position: relative;
}
.content{
width: 400px;
background: #ccc;
height: 70px;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
4、absolute + translate
<h2>absolute + margin: auto</h2>
<div class="box box6">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
height: 250px;
border: 1px solid #f00;
margin: auto;
position: relative;
}
.box5 .content{
width: 400px;
background: #ccc;
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%, -50%);
}
5、Flex + align-items
<h2>Flex + align-items</h2>
<div class="box box7">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
height: 250px;
border: 1px solid #f00;
margin: auto;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 400px;
background: #ccc;
}
6、Flex + margin
由于Flex元素对空间解读的特殊性,我们只要在父层元素设定display:flex,接着在需要垂直居中的元素上设定margin:auto,即可自动居中
<h2>.Flex + margin</h2>
<div class="box box9">
<div class="content">
立马来看实际完成的
效果吧!別忘了拖拉一下窗口看看 RWD 效果喔! </div>
</div>
h2{
text-align: center;
}
.box{
width: 500px;
height: 250px;
border: 1px solid #f00;
margin: auto;
display: flex;
}
.content{
width: 400px;
background: #ccc;
margin: auto;
}