I'm trying to make a div
that stretches to fit its content, up to some maximum width, after which the content should wrap.
Using an absolutely positioned div
works fine -- unless its parent's width is limited. When its parent's width is limited, the absolutely positioned div
acts as though its max-width
is the width
of its parent.
I'd essentially like for the absolutely positioned div
to "pretend" its parent has 100% width, and give me the nice "stretch-to-fit" behavior, while honoring the max-width
I set on it.
In the below example, I'd like the first .abs
to work, even though it is a child of a "skinny" div.
.parent {
position: relative;
background: #EEE;
width: 100px;
}
.abs {
position: absolute;
max-width: 200px;
/* width: auto, but ignore parent! */
}
.parent2 {
margin-top: 150px;
background: rgba(0,128,0,.1);
width: 100px;
}
<div class="parent">
<div>
Doesn't work.
</div>
<div class="abs">
This wraps after 100px, because it's parent has 100px width.
</div>
</div>
<div class="parent2">
<div>
Does work.
</div>
<div class="abs">
This wraps at 200px, because it's parent is as wide as the viewport, so it honors the max-width of 200px.
</div>
</div>
This is somewhat solved by wrapping abs
in an absolute div that has a much wider width than the relative
parent. The problem now becomes sizing wrapper
to stretch to the right of the viewport, which is a topic for another question.
.parent {
position: relative;
background: #EEE content-box; /* Color only the content */
width: 100px;
}
.abs-wrapper {
position: absolute;
width: 800px;
}
.abs {
position: absolute;
max-width: 200px;
border: 1px solid gray;
}
<div class="parent">
<div>
Doesn't work.
</div>
<div class="abs-wrapper">
<div class="abs">
This correctly wraps after 200px, because it's parent is a wrapper with a very large width. Thus, this div will stretch-to-fit, and also honor max-width.
</div>
</div>
</div>
<div class="parent" style="margin-top: 150px">
<div>
Doesn't work.
</div>
<div class="abs-wrapper">
<div class="abs">
< 200px shrinks to fit.
</div>
</div>
</div>