user3761386
user3761386

Reputation: 49

Absolute 100% width div overflows one side

HTML

<header>
    <div class="container">
        <div class="parent">
            <div class="child"></div>
        </div>
    </div>
</header>

CSS

header .parent{ 
           text-align:left;
           position: absolute;
           z-index: 2;
           margin-top: 15%;
        }
header .parent .child{
              /*Nothing here yet*/           
        }

I want .parent to be like this enter image description here When I set .parent width:100%, I have this enter image description here

Left side of .parent is correct but the other overflows
I don't want to use position: relative on .container because .parent will be covered by other divs outside header, even I tried to use z-index
What is the problem here ? Can anybody help me ?

Upvotes: 0

Views: 673

Answers (2)

Rovi
Rovi

Reputation: 259

.container class needs to have position: relative. As you have not set the relative container to the absolute div, it is considering the body width

.container {
    position: relative;
}

Upvotes: 0

Marc Audet
Marc Audet

Reputation: 46785

You need to set two or more of the offsets (top, left, right, bottom) for the absolutely positioned element.

In the example below, I created a header with a block border that is 100px in height and it contains .container that is half the height and has 20px margins.

For example, if you want the left and right edges of .parent to coincide with the edges of .container, set the left and right offsets to 20px.

You can control the vertical placement by assigning a value to top.

If you don't specify the offset values, they default to values corresponding to the position of the element that it would have were it in the regular flow of content.

In your original example, the left edge of .parent would correspond to the left edge of .container, since the left edge of .parent would be start at the left edge of .container, and then if you set the width: 100%, this would force the right edge to correspond to 100% of the window width to the right of the default left edge, which causes the overflow.

To fully appreciated what is happening here, you need to read the CSS specification about absolute positioning, namely:

http://www.w3.org/TR/CSS2/visudet.html#abs-non-replaced-width

especially the concept of the static-position containing block.

body { margin: 0;}
header .parent {
  border: 1px dashed red;
  position: absolute;
  height: 50%;
  top: 120px;
  left: 20px;
  right: 20px;
}

header { border: 1px solid black; height: 100px; }
.container { border: 1px dotted blue; height: 50%; margin: 20px;}
<header>
  <div class="container">
    <div class="parent">
      <div class="child"></div>
    </div>
  </div>
</header>

Upvotes: 1

Related Questions