1、display:table和diaplay:table-cell
table具备垂直居中的属性,所以很容易通过属性就能实现。
<style>
.container {
display: table;
}
.inner {
display: table-cell;
vertical-align:middle;
text-align:center;
}
</style>
<div class="container">
<div class="inner">
you own content
</div>
</div>
这种情况下,我们可以通过随意改变.inner的宽高,当内部的内容仍然保持居中状态。
2、position:absolute、50%和translate
在css3里面提供了translate函数,它的主要作用是位移,传给transform属性。
<style>
.container {
position: relative;
}
.inner {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
<div class="container">
<div class="inner">
your own content
</div>
</div>
5、css3 flex
css3新增了布局相关的属性,其中flex布局可以非常简单地帮我们实现我们想要的效果。
this is a box fixed in center of screen
The second line
The second line
作者:指尖跳动
链接:https://www.jianshu.com/p/69c570f4c1cb
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。