[英]margin: auto doesn't center?
我試圖將div居中放置在文檔上,並且它在水平方向上起作用,但在垂直方向上不起作用:
width: 950px;
height: 630px;
background: #FFFFFF;
margin: auto;
不應該設置margin: auto
將其margin: auto
放置在其所在位置(在本例中為頁面本身)的中心嗎? 我曾經有一個解決方法,但無法使其正常工作。 知道我在做什么錯也很高興,所以我可以停止這樣做。
margin: auto
不垂直對齊元素。
如果必須支持較舊的瀏覽器,則必須為div定義一個固定的高度:
div {
position: relative;
top: 50%;
width: 750px;
height: 500px; /* sample. adjust as needed */
margin: -250px auto 0; /* half the height */
}
這是小提琴: http : //jsfiddle.net/2qmVX/
如果您不關心IE8及以下版本,則可以保留流體高度:
div {
position: relative;
top: 50%;
margin: auto;
transform: translateY(-50%);
/* add prefixed versions... */
}
這是小提琴: http : //jsfiddle.net/VMaVM/ (請記住:僅適用於現代瀏覽器)。
更新:正如@FabrícioMatté指出的那樣,您還必須將100%的高度應用於html
和body
元素:
html, body {
height: 100%;
}
參見上面的演示。
正確的垂直居中甚至是CSS3都沒有涵蓋的內容。
幸運的是,由於您具有固定的高度,因此可以操縱top
/ left
屬性,並使用負margin-top
和margin-left
來實現所需的行為,並且具有absolute
位置:
background: #FFFFFF;
width: 950px;
height: 630px;
top: 50%;
left: 50%;
margin: -315px 0 0 -425px; /*top is negative half of height, same for width*/
position: absolute;
請注意,在小於div
分辨率下,負邊距可能會表現出意外情況。
這是使用表的一種更駭人聽聞的方法。 基本思想是,將vertical-align:middle
CSS屬性應用於表時,其效果與舊的valign="center"
屬性相同。 因此,HTML如下所示:
<table class="vcenter"><tr><td>
<div id="myDiv">This is a centered div</div>
</td></tr></table>
和CSS:
.vcenter {
vertical-align: middle;
width: 100%;
height: 100%;
}
#myDiv {
background: #FFF;
width: 950px;
height: 630px;
margin: 0 auto;
}
html, body { height: 100%; }
這種方法的優勢在於它是完全跨瀏覽器的-在IE6及更高版本,Firefox,Chrome,Opera和Safari上進行了測試。 我沒有在移動瀏覽器上進行測試,盡管它可以工作。 此外,它也沒有小分辨率的滾動問題。 我在我的一個生產站點中將這種hack用於集中模態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.