css布局------塊元素水平垂直居中的四種方法


HTML

<div class="parent answer-1">
<div></div>
</div>

CSS

.parent {
width: 800px;
height: 800px;
border: 1px solid red;
}
.parent div {
width: 200px;
height: 200px;
border: 1px solid red;
}

/*方法1:dispaly:table-cell*/
.answer-1 {
display: table-cell;
vertical-align: middle;
}
.answer-1 div {
margin: auto;
}
/*方法2:絕對定位(高度必須固定)*/
.answer-2 {
position: relative;
}
.answer-2 div {
position: absolute;
/*垂直居中*/
top: 0;
bottom: 0;
margin-top: auto;
margin-bottom: auto;
/*水平居中*/
left: 0;
right: 0;
margin-left: auto;
margin-right: auto;
}
/*方法3:彈性布局(高度可不固定)*/
.answer-3 {
display: flex;
/*垂直居中*/
align-items: center;
/*水平居中*/
justify-content: center;
}
/*方法4:絕對定位 + 2d轉換(高度可不固定)*/
.answer-4 {
position: relative;
}
.answer-4 div {
position: absolute;
/*垂直居中*/
top: 50%;
/*水平居中*/
left: 50%;
transform: translate(-50%,-50%);
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM