web開發(fā)常用的幾種居中形式
時(shí)間:2023-07-03 18:12:01 | 來源:網(wǎng)站運(yùn)營
時(shí)間:2023-07-03 18:12:01 來源:網(wǎng)站運(yùn)營
web開發(fā)常用的幾種居中形式:水平居中:
要居中的元素A有width屬性
給元素A添加margin:0,auto;
ps:
此外,margin: auto;和margin:0 auto;產(chǎn)生同樣效果的原因移步
要居中的元素B沒有width屬性
給B添加display:inline-block屬性,并在B的外面包一層div且添加text-align:center;
ps:text-align:center是讓塊狀里面的元素(比如文字)居中。
要居中的元素C 是絕對(duì)定位的也就是其position為absolute
給C添加margin: auto; top:0; left:0; right:0; bottom:0; 以及width和height屬性 ,并確保C的外層父元素position: relative;
ps:
設(shè)置top,left,bottom,right 屬性 把元素充滿了容器,同時(shí)自身指定了寬度,總寬度(固定) = width(固定) + margin-left + margin-right;
當(dāng)margin設(shè)置為auto的時(shí)候,左右邊距會(huì)平分,元素自然就居中了(且是水平垂直居中)
水平垂直居中:
要居中的元素C沒有width屬性及height屬性
給C的外層父元素添加display: flex; align-items: center; justify-content: center; 屬性(注意瀏覽器的兼容性)
or
給C添加margin: auto; 并且確保C的外層父元素 display: flex; (注意瀏覽器兼容性)
ps: flexBox的知識(shí)請(qǐng)移步阮一峰大神的博客
針對(duì)文本內(nèi)容的垂直居中:
父元素有width和height屬性以及text-align: center; 同時(shí)給要居中的元素D添加line-height為父元素的height值
ps: line-height 垂直居中原理 請(qǐng)移步
all.
by 潘小閑
簡書傳送門