簡體   English   中英

如何水平和垂直對齊固定位置的div?

[英]How to align horizontally and vertically to a fixed positioned div?

<div id="someid">some text here</div>

CSS ...

#someid{position: fixed; width: 500px; height: 30px;}

我想絕對定位在水平方向和垂直於窗口的中心嗎?

fixed位置后,您將無法相對定位div。 您必須通過javascript計算頂部和左側的值。 您可以通過編寫以下命令將其位置水平居中:

width: #SOMEWIDTH#px;
margin: 0 auto;

為了使邊緣位置成為中心的div,必須設置width屬性。 自動頁邊距不會影響垂直位置。

#someid{
position: 
fixed; 
width: 500px; 
height: 30px; 
right:50%; 
margin-right:-250px;
}

負邊距用於修復瀏覽器將div的右側視為距瀏覽器窗口右側50%的偏移量。

要使其垂直居中,您可能要嘗試使用其垂直位置進行相同的操作(雖然我以前沒有做過,但這里沒有保證)。

例如:

top:50%;
margin-top:-15px;

A little more thorough explanation: When #someid is placed 50% from the right it is positioned so that it is 50% of its parent's total width away from the parent's right border. 更徹底的解釋:將#someid放置在距離右側50%的位置時,它的位置應是其父級總寬度的50%,遠離父級的右邊界。 但是,這並不是從#someid的中心到其父元素的右邊界,而是從#someid的右邊到其父元素的右邊。 當然,這並不是#someid的中心,它仍然偏移了其寬度的一半。

這就是為什么我們使用負邊距來抵消它的原因。 負邊距必須是#someid寬度的一半,以彌補我們將其放置在距其父元素右側50%的右側時發生的向左偏移。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

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