不固定高宽div垂直居中的方法
1、伪元素和 inline-block / vertical-align
<style>
.box-wrap:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; //微调整空格
}
.centered {
display: inline-block;
vertical-align: middle;
}
</style>
<div class="box-wrap" style="height: 200px; background-color: #ccc; text-align: center;" >
<div class="centered">
<h1>方案一</h1>
<p>我是伪类,看我是否垂直居中</p>
</div>
</div>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/d7155240290c5f7a627af180be490980.jpeg)
该方法非常巧妙的解决了垂直居中问题,可以作为参考~
2、css3—flex
<style>
.box-wrap {
height: 300px;
justify-content:center;
align-items:center;
display:flex;
background-color:#666;
}
</style>
<div class="box-wrap">
<div class="centerd">我是css3-flex</div>
</div>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/19013ccaea510d336497e0ba817bcdb6.jpeg)
css3属性~不兼容ie8以下
3、css3—transform
<style>
.box-wrap {
width:100%;
height:300px;
background:rgba(0,0,0,0.7);
position:relative;
}
.box-content{
position:absolute;
background:pink;
left:50%;
top:50%;
transform:translateX(-50%) translateY(-50%);
-webkit-transform:translateX(-50%) translateY(-50%);
}
</style>
<div class="box-wrap">
<div class="box-content">我是css3-transform</div>
</div>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/b7e6c740547ba4a1905c289f480ec2d2.jpeg)
css3属性~不兼容ie8以下
4、设置margin:auto来达到效果
<style>
.box-wrap {
position: relative;
width:100%;
height:300px;
background-color:#f00;
}
.box-content{
position: absolute;
top:0;
left:0;
bottom:0;
right:0;
width:50%;
height:50%;
margin:auto;
background-color:#ff0;
}
</style>
<div class="box-wrap">
<div class="box-content">我是auto</div>
</div>
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/bd72917e455a84d9adda641b9e81e666.jpeg)
该方法得严格意义上的非固定宽高,而是50%的父级的宽高。视觉上可以达到效果,如果是集中有类似的需求可以用此方法。