首頁  >  文章  >  web前端  >  css中如何做到居中效果

css中如何做到居中效果

迷茫
迷茫原創
2017-01-23 14:08:561442瀏覽

我們都知道 margin:0 auto; 的樣式能讓元素水平居中,而 margin: auto; 卻無法做到垂直居中…直到現在。但是,請注意!想讓元素絕對居中,只需要聲明元素高度,並且附加以下樣式,就可以做到:

.Absolute-Center {
  margin: auto;
  position: absolute;
  top: 0; left: 0; bottom: 0; right: 0;
}

我並不是第一個發現這種方法的人(不過我還是敢把它叫做“完全居中”) ,它有可能是種非常普遍的技巧。但大多數介紹垂直居中的文章中並沒有提到這種方法。

以前從未用過這種方法的我想試試,看看這種」完全居中」的方法到底有多麼神奇。 好處:

  • 跨瀏覽器,相容性好(無需hack,可兼顧IE8~IE10)

  • 無特殊標記,樣式更精簡

  • 自適應佈局,可以使用百分比和最大最小高寬度等樣式

  • 居中時不考慮元素的padding值(也不需要使用box-sizing樣式)

  • 佈局塊可以自由調節大小

  • img的圖像也可以使用? :

必須聲明元素高度

  • 推薦設定overflow:auto;樣式避免元素溢出,顯示不正常的問題

  • 這種方法在Windows Phone上不起作用

  • :Chrome、Firefox、Safari、Mobile Safari、IE8-10。 “完全居中”經測試可以完美地應用在最新版本的Chrome、Firefox、Safari、Mobile Safari中,甚至也可以運行在IE8~IE10上
對照表

“完全居中”並不是本篇文章中唯一的選項。要做到垂直居中,還有其他方法,各有各的長處。採取什麼樣的方法,取決於你所支援的瀏覽器,以及現有標籤的結構。下面這張對照表能夠幫你選出最符合你需求的方法。

說明

css中如何做到居中效果

在研究了規範和文檔後,我總結出了「完全居中」的工作原理:1. 在普通文檔流裡,margin: autouto;設定元素的margin-top和margin-bottom為0。 W3.org:?If 'margin-top', or 'margin-bottom' are 'auto', their used value is 0.

2. 設定了position: absolute; 的元素會變成塊元素,並脫離普通文檔流。而文件的其餘部分照常渲染,元素像是不在原來的位置。 Developer.mozilla.org:?…an element that is positioned absolutely is taken out of the flow and thus takes up no space

3. 設定了top: 0; left: 0; bottom: 0; right: 0 樣式的樣式的樣式塊元素會讓瀏覽器為它包裹一層新的盒子,因此這個元素會填滿它相對父元素的內部空間,這個相對父元素可以是是body標籤,或者是一個設置了position: relative; 樣式的容器。 Developer.mozilla.org:?For absolutely positioned elements, the top, right, bottom, and left properties specify offsets from the edge of the element's containing block (what the element is positioned relative to).

。寬高以後,瀏覽器會阻止元素填滿所有的空間,根據margin: auto; 的要求,重新計算,並包裹一層新的盒子。 Developer.mozilla.org:?The margin of the [absolutely positioned] element is then positioned inside these offsets.

5. 既然塊元素是絕對定位的,又脫離了普通文檔流,因此瀏覽器在包裹盒子之前會為margin-top和margin-bottom設定一個相等的值。 W3.org:?If none of the three [top, bottom, height] are 'auto': If both 'margin-top' and 'margin-bottom' are 'auto', solve the equation under the extra constraint that the two margins get equal values.?AKA: center the block vertically

使用“完全居中”,有意遵照了標準margin: auto; 樣式渲染的規定,所以應在與標準兼容的各種瀏覽器中起作用。

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn