图像背景位置为50%左侧居中的背景图像,但50%留在绝对定位元素中不会使div元素居中为什么?
这是代码:
<div style="position:relative;height:100px; background:url(images/demo.jpg) no-repeat 50% 0">
<div style="min-height:40px; width:140px; background-color:#aaa;position:absolute;top:0;left:50%;">
heloo this is just a demo
</div>
3 回答
background-position
属性中声明的相对定位会考虑所定位图像的尺寸,而使用CSS位置属性(top,right,bottom,left
)时,只考虑相对父级的尺寸 .考虑它的好方法是使用最小值和最大值:
使用0%时,效果相同:
背景定位图像拥抱包含元素的左边缘
绝对定位的元素拥抱相对父级的左边缘
100%,效果明显不同:
背景定位图像拥抱包含元素的右边缘
绝对定位元素's left edge lines up with relative parent' s右边缘
要解决您的问题,您可以将元素宽度的一半的负余量添加到第二个div:
孩子的左侧
div
将在div
的父母div
的中途 . 让孩子居中div
使用left: 50%;
和margin-left: -(half the width of child div)
为了简单起见,我建议只需删除
position:absolute;top:0;left:50%;
并使用margin: 0 auto;
代替 .