【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!
生活随笔
收集整理的這篇文章主要介紹了
【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
div水平垂直居中
假設結構為此,2個div嵌套
<div class="box"><div class="content"></div> </div>?
實現方式1:
absolute絕對定位+margin位移實現
這種方式適用于內外2個div的寬高是已知時使用。外層使用相對定位,內層使用絕對定位50%,并使用位移寬高的一半使之居中
.box{background-color: yellow;width: 300px;height: 300px;position: relative;border: 1px solid red; } .content{background-color: red;width: 100px;height: 100px;position: absolute;top: 50%;left: 50%;margin: -50px 0 0 -50px; }實現方式2:
transform實現
這種方式,幾乎和上一直一樣。但是如果子div寬高不定時,也可以實現居中。比第一種好點。
.box{background-color: yellow;width: 300px;height: 300px;position: relative;border: 1px solid red; } .content{background-color: red;position: absolute;width: 100px;height: 100px;top: 50%;left: 50%;transform: translate(-50%,-50%); }實現方式3:
flex布局實現,使用justify-content和align-items實現
.box{background-color: yellow;width: 300px;height: 300px;display: flex;/*flex布局*/justify-content: center;/*水平居中*/align-items: center;/*垂直居中*/border: 1px solid red; } .content{background-color: red;width: 100px;height: 100px; }?
盒子模型
盒子模型由內容、內邊距、邊框、外邊距組成。
上方是一張圖,下方是盒子模型
<img src="https://www.runoob.com/try/demo_source/250x250px.gif" width="250" height="250"> <div class="ex">一個盒子</div> .ex{width: 220px;padding: 10px;border: 5px solid red;margin: 0; }這是盒子結構:
?
這是內容:
這是內邊距:
這是邊框:
外邊距為0:
?
轉載于:https://www.cnblogs.com/wuhairui/p/10944661.html
總結
以上是生活随笔為你收集整理的【css】常用的几种水平垂直居中方式与盒子模型,面试经常问到!的全部內容,希望文章能夠幫你解決所遇到的問題。