leonheess
leonheess

Reputation: 21361

How can I shrink the parent div to the size of its child?

I have boxes with different dimensions - some fixed and some dynamic. I need a wrapper-div that applies a border without changing the HTML code or the child's CSS (only change .one's CSS)

How can I do this so both boxes in the below snippet keep their respective size but the parent is not larger than them?

.one {
  border: solid red 1px;
}

#two {
  height: 60px;
  width: 320px;
  background-color: firebrick;
}

#three {
  height: 60px;
  width: 100%;
  background-color: lightcoral;
}
<div class="one">
  <div id="two"></div>
</div>
<br>
<div class="one">
  <div id="three"></div>
</div>

Upvotes: 1

Views: 2246

Answers (2)

Temani Afif
Temani Afif

Reputation: 272789

If it's only about a visual style use a filter like below. The more filter you add the more you get close to a solid edge

.one {
  filter:
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue)
    drop-shadow(0 0 0.5px blue);
}

#two {
  height: 60px;
  width: 320px;
  background-color: firebrick;
}

#three {
  height: 60px;
  width: 100%;
  background-color: lightcoral;
}
<div class="one">
  <div id="two"></div>
</div>
<br>
<div class="one">
  <div id="three"></div>
</div>

Upvotes: 1

0stone0
0stone0

Reputation: 43954

There are many ways to 'shrink' .two.

My approach would be using a static width, with an inline-block on .one:

.one {
  border: solid red 1px;
  display: inline-block;
}

.two {
  height: 60px;
      width: 320px;
  max-width: 320px;
  background-color: firebrick;
}
<div class="one">
  <div class="two"></div>
</div>


Another option, using display: inline-flex; on the .one, with an static with on .two:

.one {
  border: solid red 1px;
  display: inline-flex;
}

.two {
  height: 60px;
      width: 320px;
  max-width: 320px;
  background-color: firebrick;
  display: inline-table;
}
<div class="one">
  <div class="two"></div>
</div>


Using flex, you can let .two 'grow' to the size of .one, the only downside to this, is that you'll need the 320px on .one, but in the end, using flex offer more options

.one {
  border: solid red 1px;
  display: inline-flex;
  
  height: 60px;
  width: 320px;
}

.two {
  flex-grow: 1;
  background-color: firebrick;
}

div {
  display: flex;
}
<div class="one">
  <div class="two"></div>
</div>


As @Tacoshy mentioned in the comments, another way is using width: min-content on the .one. Should be noted that IE doesn't yet support that property.

.one {
  border: solid red 1px;
  display: inline-flex;
  
  width: min-content;
}

.two {
  height: 60px;
  min-width: 320px;
  background-color: firebrick;
}
<div class="one">
  <div class="two"></div>
</div>

Upvotes: 4

Related Questions