日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 前端技术 > CSS >内容正文

CSS

CSS实现垂直居中的5种方法

發布時間:2023/12/10 CSS 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 CSS实现垂直居中的5种方法 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

方法一

這個方法把一些?div?的顯示方式設置為表格,因此我們可以使用表格的?vertical-alignproperty 屬性。

<div id="wrapper"> <div id="cell"><div class="content">Content goes here</div></div></div>


#wrapper {display: table; }#cell {display: table-cell;vertical-align: middle; }


優點:

  • content?可以動態改變高度(不需在 CSS 中定義)。

  • 當?wrapper?里沒有足夠空間時,?content?不會被截斷

缺點:

  • Internet Explorer(甚至 IE8 beta)中無效,許多嵌套標簽(其實沒那么糟糕,另一個專題)

方法二:

這個方法使用絕對定位的?div,把它的?top?設置為?50%,top?margin?設置為負的?content?高度。這意味著對象必須在 CSS 中指定固定的高度。

因為有固定高度,或許你想給?content?指定?overflow:auto,這樣如果?content?太多的話,就會出現滾動條,以免content?溢出。

<div class="content"> Content goes here</div> #content {position: absolute;top: 50%;height: 240px;margin-top: -120px; /* negative half of the height */}

優點:

  • 適用于所有瀏覽器

  • 不需要嵌套標簽

缺點:

  • 沒有足夠空間時,content?會消失(類似div?在?body?內,當用戶縮小瀏覽器窗口,滾動條不出現的情況)

方法三

這種方法,在 content 元素外插入一個 div。設置此?div?height:50%; margin-bottom:-contentheight;。?
content 清除浮動,并顯示在中間。

<div id="floater"> <div id="content">Content here</div></div>

#floater {

? ?float: left;height: 50%;margin-bottom: -120px; }#content {clear: both;height: 240px;position: relative; }


優點:

  • 適用于所有瀏覽器

  • 沒有足夠空間時(例如:窗口縮小)?content?不會被截斷,滾動條出現

缺點:

  • 唯一我能想到的就是需要額外的空元素了(也沒那么糟,又是另外一個話題)

方法四

這個方法使用了一個?position:absolute,有固定寬度和高度的?div。這個?div?被設置為?top:0; bottom:0;。但是因為它有固定高度,其實并不能和上下都間距為 0,因此?margin:auto;會使它居中。使用?margin:auto;使塊級元素垂直居中是很簡單的。

<div id="content"> Content here</div>


#content {position: absolute;top: 0;bottom: 0;left: 0;right: 0;margin: auto;height: 240px;width: 70%; }


優點:

  • 簡單

缺點:

  • IE(IE8 beta)中無效

  • 無足夠空間時,content?被截斷,但是不會有滾動條出現

方法五

這個方法只能將單行文本置中。只需要簡單地把?line-height?設置為那個對象的?height?值就可以使文本居中了。

<div id="content"> Content here</div> #content {height: 100px;line-height: 100px; }

優點:

  • 適用于所有瀏覽器

  • 無足夠空間時不會被截斷

缺點:

  • 只對文本有效(塊級元素無效)

  • 多行時,斷詞比較糟糕

這個方法在小元素上非常有用,例如使按鈕文本或者單行文本居中。


總結

以上是生活随笔為你收集整理的CSS实现垂直居中的5种方法的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。