css如何实现div高度不固定垂直居中?

  • 该方法适用于所有品牌的电脑。

CSS不固定高宽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>

1.jpg-600

该方法非常巧妙的解决了垂直居中问题,可以作为参考~

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>

2.jpg-600

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>

3.jpg-600

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>

4.jpg-600

该方法得严格意义上的非固定宽高,而是50%的父级的宽高。视觉上可以达到效果,如果是集中有类似的需求可以用此方法。

以上就是css如何实现div高度不固定垂直居中?的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » CSS3 答疑