[英]Align an anchor vertically and horizontally within an absolute positioned 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.