完全利用CSS實現元素置中

來源:互聯網
上載者:User
這次給大家帶來完全利用CSS實現元素置中,利用CSS實現元素置中的注意事項有哪些,下面就是實戰案例,一起來看一下。

前言

記得有次找工作面試的時候,一面試官問了一個CSS方面的問題:如何讓元素在瀏覽器視窗中上下左右置中。我記得當時給了個答案是,先用JS擷取瀏覽器視窗高度,然後給body設定line-height為視窗高度並設定text-align:center, 接著再設定該元素display:inline-block和vertical-align:middle。唉,現在想想自己都覺得累。

難道就一定要用到JS嗎?就不能有一種只用CSS方法就能實現元素置中的方法嗎?答案是,有!而且方法遠不止一種!

一、line-height置中法

父元素:text-align: center; line-height:600px; font-size: 0;

子項目:display: inline-block; vertical-align: middle;

註:600px必須為父元素的高度,這裡還需注意的一點是font-size需設為零,若未寫該屬性將導致元素並不能精確垂直置中。該方法即為我面試時所答的方法,缺點很明顯,父元素高度須確定。(相容IE8+)

二、table-cell置中法

父元素:display: table-cell; text-align: center; vertical-align: middle;

子項目:display: inline-block;

註:相容IE8+

三、上下左右定位+margin置中法

父元素:position: relative;

子項目:position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto;

註:相容IE8+

四、50%定位+margin置中法

父元素:position: relative;

子項目:position: absolute; left: 50%; top: 50%; margin: -200px 0 0 -200px;

註:200px須為該子項目的寬高的一半。例如該子項目寬為100px,高為50px,那麼margin取值為-25px 0 0 -50px。該方法缺點是須確定子項目寬高。(相容IE8+)

五、50%定位+translate置中法

父元素:position: relative;

子項目:position: absolute; left: 50%; top: 50%; transform: translate(-50%,-50%);

註:該方法使用了CSS3 transform屬性,適合用於移動端。(相容IE9+)

六、Flexbox置中法

父元素:display: flex; justify-content: center; align-items: center;

註:該方法使用了Flexbox彈性布局,移動端相容性也存在很大問題。(相容IE10+)

七、Flexbox+margin置中法

父元素:display: flex;

子項目:margin: auto;

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

focus-within的使用詳解

虛擬元素::before與::after使用詳解

font-size-adjust屬性如何最佳化網頁排版

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.