本文首發於個人公衆號:前端新世界
歡迎關注css
本文將討論可用於居中對齊元素的6種CSS技術(按照最佳實踐排序),以及每一種技術最適合應用的場景。這裏,居中對齊指的是將元素放置在其父元素的水平和垂直中心。前端
.center
類表明要居中對齊的元素flex
.parent
類表明其父元素。flexbox
何時用:插件
這個思路是使用絕對定位——top
和left
50%,而後應用負變換。top
和left
中使用的值根據父元素的尺寸解析,而translate
方法中的值根據元素自己的尺寸解析。code
.center { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); }
何時用:orm
這個思路是使父容器成爲flexbox並使用flex
屬性將元素沿水平和垂直方向居中,以下所示。排序
.parent { display: flex; justify-content: center; align-items: center; }
當有多個元素須要一個在另外一個元素上方堆疊,並使該元素堆疊在其中心時,咱們只需添加如下代碼行:教程
flex-direction: column;
何時用:開發
這個思路是再次使用相似於變換技術的絕對定位,但應用的是元素寬度和高度一半的負邊距而不是平移。
$w: 200px; /* SCSS 變量 */ $h: 100px; /* SCSS 變量 */ .center { position: absolute; top: 50%; left: 50%; margin: -50px -100px; /* Negative margin of half the width and heigh */t }
爲了使這段代碼更通用,咱們使用calc()
屬性,以下所示:
(#{$h} / 2) - 一半高度
(#{$h} / 2) * -1) - 一半高度的負值
這樣就能夠:
margin: calc((#{$h} / 2) * -1) calc((#{$w} / 2) * -1);
何時用:
這個思路是建立一個網格容器並將邊距設置爲auto
。在非網格容器中,當margin
設置爲auto
時,margin-top
和bottom
取值爲0。
可是,在網格容器中,margin-top
和bottom
平均分配可用空間,從而使元素居中。
.parent { display: grid; } .center { margin: auto; }
另外一種使用網格來實現居中的方法是:
.parent { display: grid; place-items: center; }
不建議將此技術用於中心對齊,但它也是可行的。
何時用:
這個思路是爲已知固定高度的容器設置固定的垂直填充,並容許子元素佔據最大高度和自動邊距。
.parent { height: 600px; //Fixed height padding: 200px 0; //Fixed vertical padding } .center{ margin: 0 auto; height: 100%; // Child takes max height }
這個技術如今用得比較少,可是也值得借鑑。而且,它確實也是可行的。
這個思路是使用display
強制父級表現得像一個表格單元格。而後使用vertical align
屬性進行垂直居中,使用margin auto
進行水平居中。
.parent { display: table-cell; vertical-align: middle; } .center{ margin: auto; }
以上總結了居中對齊元素的6種方法。
水平居中一般用於標題樣式和頁腳,並結合均勻的填充或邊距。
何時用:
inline-*
類型元素時;linline-*
包括inline
、inline-block
、inline-flex
、inline-table
等。.parent { text-align: center; }
它還能夠居中塊類型子元素,但咱們不推薦這麼作。
何時用:
.center { margin: 0 auto; }
感謝閱讀!
每日分享前端插件和前端開發教程,歡迎掃碼關注個人公衆號:前端新世界