簡體   English   中英

保證金:汽車不居中?

[英]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%的高度應用於htmlbody元素:

html, body {
    height: 100%;
}

參見上面的演示。

正確的垂直居中甚至是CSS3都沒有涵蓋的內容。

幸運的是,由於您具有固定的高度,因此可以操縱top / left屬性,並使用負margin-topmargin-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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM