div和img垂直居中的方法

div垂直居中可以使用height和line-height,多个div的话就不适用了.

1.可以使用table布局垂直居中

<div class="parent">
    <div class="child">内容</div>
</div>


.parent {
display: table;
}

.child {
display: table-cell;
vertical-align: middle;
}

2.使用flex垂直居中

<div class="parent">
    <div class="child">内容</div>
</div>


.parent {
display: flex;
justify-content: center;/*实现水平居中*/
align-items:center; /*实现垂直居中*/
}

.child {
width: 100px; 
height: 100px;
}

3.利用transform+relative实现的居中

<div class="parent">
    <div class="child">内容</div>
</div>


.parent {
position: absolute;
}

.child {
width: 300px;
height: 150px;

position: relative;
top: 50%;
left: 50%;
transform: translateX(-50%) translateY(-50%);
}

 

img的垂直居中在img外的div设置 margin: 0 auto就可以了

 

posted @ 2021-06-04 11:48  何以平天下  阅读(310)  评论(0编辑  收藏  举报