I have a div which is only as wide as its contents, but I'm trying to make it so that a certain element is ignored when determining the div's size.
<div id="parent">
<div class="ignore" style="width: 20px"></div>
<div style="width: 10px"></div>
</div>
I want to make it so that the width of the parent div is 10px
As suggested by these answers, I tried adding position:absolute
to .ignore
, but this takes it out of the document flow, which is not what I want. Is there some way to keep .ignore
in the document flow, but have it overflow past the 10px width?
This is what I want:
Not this:
You can simply use the CSS display property with the value inline-block to make a <div> not larger than its contents (i.e. only expand to as wide as its contents).
How does CSS process whitespace? Most whitespace characters are ignored, not all of them are. In the earlier example one of the spaces between "Hello" and "World!" still exists when the page is rendered in a browser.
Add a big negative margin to the ignore
element while setting the width.
#parent {
background:red;
padding:5px;
display:inline-block;
}
#parent > div {
height:20px;
background:blue;
margin-bottom:5px;
}
.ignore {
margin-right:-500px;
/*to illustrate*/
animation:change 2s linear infinite alternate;
}
@keyframes change {
from {width:10px;}
to {width:100px;}
}
<div id="parent">
<div class="ignore"></div>
<div style="width: 30px"></div>
<div></div>
<div style="width: 40px"></div>
<div class="ignore"></div>
<div style="width: 30px"></div>
</div>
Or use only the negative margin to set the width. Note that the final width will be the sum of the biggest width inside the parent + the margin you set (not only the margin)
#parent {
background:red;
padding:5px;
display:inline-block;
}
#parent > div {
height:20px;
background:blue;
margin-bottom:5px;
}
.ignore {
/*to illustrate*/
animation:change 2s linear infinite alternate;
}
@keyframes change {
from {margin-right:-10px;}
to {margin-right:-100px;}
}
<div id="parent">
<div class="ignore"></div>
<div style="width: 30px"></div>
<div></div>
<div style="width: 40px"></div>
<div class="ignore"></div>
<div style="width: 30px"></div>
</div>
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