How to restrict the width of an absolute div element within another div while maintaining its position?

1

I'd like to create a div element with dynamic width, and another element div inside it with property position: absolute e width: 100% , but not that div inside goes "over%" of div pai .

The image below demonstrates what I need, in the first example what I have, and in the second what I want.

I've been able to do this a few times, but I've never understood why it works and sometimes not. When an absolute% w / 100% width will occupy 100% of the page, and when will it occupy 100% of the available area (% with% parent)?

Note: I need this element to be absolute.

    
asked by anonymous 05.10.2015 / 16:07

1 answer

2

The div with position: absolute has the absolute positioning always referring to the div parent that has relative positioning. If no% of parent% has relative positioning, its positioning will be absolute relative to the body, that is, div will be 100% of the width of the width: 100% tag.

.relative{
  position: relative;
  width: 300px;
  height: 300px;
  background-color: black;
}

.absolute{
  position: absolute;
  width: 100%;
  height: 20px;
  background-color: red;
  top:50px;  
}
<div class="relative">
  <div class="absolute">Teste</div>
</div>

Try to remove body from position: relative to see what happens.

In this answer I'll give you more details on how absolute placement works.

EDIT

Remember that .relative is absolute with respect to the first div.absolute that contains div that is at any level above in the DOM, not necessarily the his father straight. This means that the position: relative relation does not necessarily have to be true. Other elements may exist in the middle of this hierarchy. To illustrate:

.relative{
  position: relative;
  background-color: black;
  height: 300px;
  width: 300px;
}

.middle{
  background-color: red;
  height: 150px;
  width: 150px;
}

.absolute{
  background-color: yellow;
  height: 75px;
  width: 100%;
  position: absolute;
}
<div class="relative">
  <div class="middle">
    <div class="absolute"></div>
  </div>
</div>

See that div.relative > div.absolute is relative to .absolute , ignoring .relative . If .middle contained .middle , position: relative would be relative to .absolute . If .middle is removed from position: relative , the yellow range will occupy 100% of the window (in this case, where .relative does not contain .middle ).

    
05.10.2015 / 16:15