Reputation: 921
Image background position to 50% left center the background image but 50% left in absolute positioned element doesn't center the div element why?
Here is the code:
<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>
Upvotes: 0
Views: 147
Reputation: 813
To keep things simple, I would suggest simply removing position:absolute;top:0;left:50%;
and using margin: 0 auto;
instead.
Upvotes: 0
Reputation: 19388
The left side of the child div
will be halfway across the parent div
with left: 50%;
. To center the child div
use left: 50%;
and margin-left: -(half the width of child div)
Upvotes: 0
Reputation: 16466
Relative positioning as declared in the background-position
property takes into account the dimensions of the image being positioned, whereas when using a CSS positional property (top,right,bottom,left
) only take the relative parent's dimensions into account.
A good way to think about it is using the minimum and maximum values:
To solve your problem, you can add a negative margin of half the element's width to the second div:
margin-left: -70px;
Upvotes: 2