如何将绝对定位元素在100%宽度div中水平居中? [英] How do I horizontally center an absolute positioned element inside a 100% width div?
问题描述
在下面的例子中, #logo
绝对定位,我需要它在 #header
。通常,我会对相对定位的元素做一个 margin:0 auto
,但我被困在这里。有人可以告诉我吗?
In the example below, #logo
is positioned absolutely and I need it to be horizontally centered within #header
. Normally, I would do a margin:0 auto
for relatively positioned elements but I am stuck here. Can someone show me the way?
JS Fiddle: http://jsfiddle.net/ DeTJH /
JS Fiddle: http://jsfiddle.net/DeTJH/
HTML
<div id="header">
<div id="logo"></div>
</div>
CSS
#header {
background:black;
height:50px;
width:100%;
}
#logo {
background:red;
height:50px;
position:absolute;
width:50px
}
推荐答案
如果你想在左边的属性对齐中心。
同样的事情是顶部对齐,你可以使用margin-top:(width / 2的div),概念是相同的left属性。
将标题元素设置为position:relative是重要的。
尝试:
If you want to align center on left attribute.
The same thing is for top alignment, you could use margin-top: (width/2 of your div), the concept is the same of left attribute.
It's important to set header element to position:relative.
try this:
#logo {
background:red;
height:50px;
position:absolute;
width:50px;
left:50%;
margin-left:-25px;
}
如果您不想使用计算,可以执行以下操作:
If you would like to not use calculations you can do this:
#logo {
background:red;
width:50px;
height:50px;
position:absolute;
left: 0;
right: 0;
margin: 0 auto;
}
这篇关于如何将绝对定位元素在100%宽度div中水平居中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!