How do I prevent a div from expanding in width?
I'd like .dont-expand to pretend that width: 100%; means "100%, but not counting myself". Basically, compute width: 100%; (ignoring itself), and setting that width in pixels width: Npx; -- in CSS and not JS.
.outer {
position: absolute;
border: 1px solid black;
}
/* This element sets the width of the container */
.has-width {
width: 300px;
margin-top: 10px;
background: rgba(0,128,0,.2);
border-right: 2px solid green;
color: #888;
}
.dont-expand {
/* width: ??? */
/* This would be nice */
/* expand: false; */
/* Or this */
/* width: toPx(100%); */
/* Or this */
/* width: calc(100% + 0px); */
}
<div class="outer">
<div class="dont-expand">
How do I get this text to wrap
instead of growing the container?
</div>
<div class="has-width">
I should be setting the width of "container".
</div>
</div>
jsbin link
It looks like you can make an element "appear" as 0 width to its parent, but still have it expand to the parent's width by doing: width: 0px; min-width: 100%.
This seems to be the cleanest, most browser-compatible solution. It also doesn't require changing the display property, which is a plus.
/* Make it "shrink-to-fit", either inline-block, or position: absolute */
.outer {
/* position: absolute; */
display: inline-block;
border: 1px solid black;
}
/* This element sets the width of the container */
.has-width {
width: 300px;
margin-top: 10px;
background: rgba(0,128,0,.2);
border-right: 2px solid green;
color: #888;
}
/* Appears as 0 width to parent, but then expands to fit. */
.dont-expand {
width: 0px;
min-width: 100%;
}
<div class="outer">
<div class="dont-expand">
How do I get this text to wrap
instead of growing the container?
</div>
<div class="has-width">
I should be setting the width of "container".
</div>
</div>
Try using
.outer {
position: absolute;
border: 1px solid black;
width: min-content;
}
This should make it so that the width of the outer box becomes as small as possible, while not squashing content.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With