版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/q821901733/article/details/78007428
三种方法实现DIV水平垂直居中
- 绝对定位 + margin 负值
/* html */
<div id="box"></div>
/* css */
#box{
height:200px;
width:400px;
background:#ccc;
position:absolute;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-200px;
}
要点:已知元素高和宽,将其绝对定位时,top,left定位50%,最后将margin-top 和 margin-left 设为高和宽的一半的负值。
- 绝对定位 + translate
#box{
height:200px;
width:400px;
background:#ccc;
position: absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
要点:可以不知道元素高和宽,将其绝对定位时,top,left定位50%,最后translate(-50%,-50%),即移动相对于自身高和宽的-50%。
- 绝对定位 + margin 自适应
#box{
height:200px;
width:400px;
background:#ccc;
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
margin: auto;
}
要点:可以不知道元素高和宽,将其绝对定位时,top,left,bottom,right设为0,同时margin 自适应。
效果图都一样,就放一张:
CSS图片水平垂直居中
/* html */
<div id="box">
<img src="./img/test.jpg" alt="">
</div>
/* css */
#box{
width: 200px;
height: 200px;
margin: 0 auto;
border: 1px solid #41b886;
text-align: center;
line-height: 200px;
}
#box img{
//图片设为70%,是为了方便查看效果
width: 70%;
vertical-align: middle;
}
最后贴上效果图: