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

Asked

Viewed 672 times

1

I’d like to create an element div with dynamic width, and another element div within this with the property position: absolute e width: 100%, but without that div from inside pass "over" the div father.

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

Exemplo

I have managed to do this a few times, but I never understood why sometimes it works and sometimes it doesn’t. When a div absolute with 100% width will occupy 100% of the page, and when it will occupy 100% of the available area (div father)?

Note: I accurate that this element div from within be absolute.

1 answer

2


To div with position: absolute has the absolute position always referring to div parent who has relative positioning. If no div parent has relative positioning, its positioning will be absolute in relation to the body, ie, width: 100% will be 100% tag width body.

.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 withdraw position: relative of .relative for you to see what happens.

In that reply give more details on how absolute positioning works.

EDIT

It is worth remembering that div.absolute is absolute with respect to first div containing position: relative which is in whichever level up in the DOM, not necessarily your direct father. That means the relationship div.relative > div.absolute need not necessarily 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 .absolute is related to .relative, ignoring .middle. If .middle contivesse position: relative, .absolute would relate to .middle. Case position: relative is withdrawn from .relative, the yellow band will occupy 100% of the window (in the current case, where .middle does not contain .relative).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.