$13.11

Make CSS max-width larger than parent

Ask a question+
2

https://jsfiddle.net/d3yns9b6/ shows how max-width doesn’t work when I want to set it to something larger than the containing element.

Since it’s absolutely positioned, it should be able to extend outside the containing element. If I set an exact value using width, it works, but then both pieces of text in the example are exactly that width.

I want them both to take up as little width as they need, up to a maximum of the amount I set (even if it exceeds the parent container).

.out {
  position: relative;
  width: 200px;
  height: 400px;
  background-color: blue;
}

.in {
  position: absolute;
  max-width: 600px;
  background-color: yellow;
}
<div class="out">
  <div class="in">
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam commodi saepe, magnam aliquid quisquam cum ex corrupti sequi aut eius harum animi vitae, exercitationem eaque tempore culpa at itaque explicabo.
  </div>
  <div class="in" style="margin-top:300px">
    Lorem
  </div>
</div>
add comment

1 Answer

1

Well, when no width is provided, it will fall back to auto, meaning it will use the width given by the parent element, regardless of absolute positioning or any max-width. So you need to specify any width, using percentage or relative units like vh or vw.

.out {
  position: relative;
  width: 200px;
  height: 400px;
  background-color: blue;
}

.in {
  position: absolute;
  width: 500%;
  max-width: 600px;
}

.in > span {
  background-color: yellow;
  display: inline-block;
}
<div class="out">
  <div class="in">
    <span>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam commodi saepe, magnam aliquid quisquam cum ex corrupti sequi aut eius harum animi vitae, exercitationem eaque tempore culpa at itaque explicabo.</span>
  </div>
  <div class="in" style="margin-top:300px">
    <span>Lorem</span>
  </div>
</div>

this might be interesting for you https://www.w3docs.com/learn-css/position.html

add comment

Your Answer