Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to ignore a certain element when determining parent's size

Tags:

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:

This

Not this:

this

like image 342
Param Avatar asked Apr 27 '19 15:04

Param


People also ask

How do you make a DIV not bigger than a parent?

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).

Does CSS ignore whitespace?

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.


1 Answers

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>
like image 61
Temani Afif Avatar answered Nov 02 '22 23:11

Temani Afif