css 常用的幾種垂直置中(包括圖片)

來源:互聯網
上載者:User

標籤:寫法   font   abs   總結   block   isp   script   wrap   缺點   

我知道現在有非常多的水平垂直置中的寫法,我就寫一些我自己常用的方法,同時說明一下優缺點
<div class="wrapper">    <div class="item"></div></div>.wrapper{width:200px;height:200px;}.item{width:100px;height:100px;}


1 `position  tranform
.wrapper{position:relative}
.item{position:absolute;top:50%;transform:translateY(-50%);}

優點:item不需要定死高度
缺點:transform需要相容一下;不過現在transform相容性還好

 

 

2 `position  margin
.wrapper{position:relative}
.item{position:absolute;top:50%;margin-top:-50px;}

優點:相容性好,
缺點:item需要定死高度,因為margin-top需要反方向移動自身高度的一半

 

 

3 `position  margin
.wrapper{position:relative}
.item{position:absolute;top:0;bottom:0;margin:auto;}

優點:相容性好,也不需要定高;

 

 

4 `display:inline-block ;line-height;vertical-align:middle;

.wrapper{line-height:200px;}
.item{display:inline-block;vertical-align:middle;}

優點:相容性好,也不需要定高;需要將block變為inline-block
vertical-align:一般都用在子項目上;

 

 

5` flex   align-items    justify-content

.wrapper{display:flex;justify-content:center;aligin-items:center}

優點:全部寫在父元素上,不定高,移動端高效;

 

 

6` flex   margin

.wrapper{display:flex;}
.item {margin:auto}

優點:不定高,移動端高效;

 

 

 

總結一下:我一般都是用第五或者第六種寫法,現在flex布局的瀏覽器支援越來越廣泛了,而且這樣布局的話,有幾個好處:

1 不需要考慮子項目的本身的height和width,容易複用,特別是寫UI組件的時候

2 不需要顧及子項目本身是塊狀元素還是內嵌元素還是內聯塊狀元素(例片),它都可以置中

注意,設為Flex布局以後,子項目的float、clear和vertical-align屬性將失效。

 

css 常用的幾種垂直置中(包括圖片)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.