Make children fill parent max-width inside an absolute context

91 views Asked by At

I have something equivalent to the second case (div group) of this simplified example, the first one is just to show that it works outside of an absolute context with the child expanding as much as it can until it reaches the parent max-width:

.abs {
  position: absolute;
  top: 50px;
}

.parent {
  /*
    This div is reused across the web with different dynamic content
    Its only constraint to the children should be a maximum width
  */
  max-width: 300px;
}

.child {
  /*+
    This is one of the multiple children the parent will have
    In this case it should should always try to grow as much as allowed by its parent
  */
  width: 100%;
  background-color: lightblue;
}
<div class='parent'>
  <div class='child'>
    Foo
  </div>
</div>

<div class='abs'>
  <div class='parent'>
    <div class='child'>
      Bar
    </div>
  </div>
</div>

Given that the absolute div is mandatory for my specific needs, is there any way to make a child element fill its parent max-width?

1

There are 1 answers

0
developer On

This is what W3C states:

Absolutely positioned elements will shrink-wrap to fit their contents unless you specify their dimensions. You can specify the width by setting the left and right properties, or by setting the width property. You can specify the height by setting the top and bottom properties, or by setting the height property.

Therefore, you need to specify width for your absolute element.

.abs {
  position: absolute;
  top: 50px;
  width: 100%;
}

.parent {
  max-width: 300px;
}

.child {
  width: 100%;
  background-color: lightblue;
}
<div class='parent'>
  <div class='child'>
    Foo
  </div>
</div>

<div class='abs'>
  <div class='parent'>
    <div class='child'>
      Bar
    </div>
  </div>
</div>

I assume that you are using some framework to accomplish your task - specifying the width can be placed inside components stylesheet, so each of the components which eventually uses it can provide preferred width (and other styling as well)