blue ghhgdtt
blue ghhgdtt

Reputation: 921

Why do background images and absolute position to 50% behave differently?

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

Answers (3)

Marc Ripley
Marc Ripley

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

dezman
dezman

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

Barney
Barney

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:

  1. With 0%, the effect is identical:
    • background-positioned image hugs the left edge of the containing element
    • absolutely positioned element hugs the left edge of the relative parent
  2. With 100%, the effect is clearly different:
    • background-positioned image hugs the right edge of the containing element
    • absolutely positioned element's left edge lines up with relative parent's right edge

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

Related Questions