水平垂直居中已知宽高的div
.test{
width: 100px;
height: 100px;
position: absolute;
background: pink;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
效果如下:
那么此方法能不能垂直居中位置宽高的div呢?答案显然不行。
水平垂直居中未知宽高的div
方法一: 用一个“ghost”伪元素(看不见的伪元素)和 inline-block / vertical-align 可以搞定居中,非常巧妙。但是这个方法要求待居中的元素是 inline-block,不是一个真正通用的方案。
<style>
html,body{
width: 100%;
height: 100%;
background-color: yellow;
}
.block {
text-align: center;
height: 100%;
}
.block:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
.center {
display: inline-block;
vertical-align: middle;
width: 50%;
}
</style>
<div class="block">
<div class="center">
水平垂直居中未知宽高的div
</div>
</div>
效果如下:
方法二: table布局,这种方法也有局限性
<style>
html,body{
width: 100%;
height: 100%;
background-color: yellow;
}
.block {
display: table;
width: 100%;
height: 100%;
}
.center {
display: table-cell;
text-align: center;
vertical-align: middle;
color:pink;
}
</style>
<div class="block ">
<div class="center">
水平垂直居中未知宽高的div
</div>
</div>
效果如下:
方法三: 以上2中方法可能都有其局限性,我介绍的第三中方法是比较成熟的不是固定高宽div的垂直居中的方法!但是方法是css3的写法,想兼容IE8的童鞋们,建议用上面的方法!
方法和我们固定高宽的差不多,但是不用margin我们用的是 translate()
<style>
html,body{
background-color: yellow;
}
.center {
background-color: pink;
position: fixed;
top: 50%;
left: 50%;
width:50%;
height: 50%;
-webkit-transform: translateX(-50%) translateY(-50%);
-moz-transform: translateX(-50%) translateY(-50%);
-ms-transform: translateX(-50%) translateY(-50%);
transform: translateX(-50%) translateY(-50%);
}
</style>
<div class="center">
</div>
效果如下:
css3 水平垂直居中未知宽高的div
<style>
html{
justify-content:center;//子元素水平居中
align-items:center;//子元素垂直居中
display:-webkit-flex;
}
</style>
<div class="center">
水平垂直居中未知宽高的div
</div>
效果如下:
运用margin:auto垂直水平居中
<style>
.father{
position:fixed;
width:100%;
height:100%;
top;0;
left:0;
background-color:yellow;
}
.son{
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
width:50%;
height:50%;
margin:auto;
background-color:pink;
}
</style>
<div class="father">
<div class="son"></div>
</div>
效果如下:
好了,以上就是我所了解的方法!