Carl Patenaude Poulin
Carl Patenaude Poulin

Reputation: 6570

How to stretch child div vertically to fill up parent div when parent div height is dynamic

Mockup:

The parent div's height is dynamic; it shrinks to fit the left-hand div (the one containing the text). I'd like the right-hand div (white background, with child img) to stretch vertically to fill the parent div. Unfortunately, height: 100% only works when the parent div's height is statically determined.

Here's what I've got right now:

.container {
  background-color: lightgray
}

.blurb {
  display: inline-block;
  padding: 2em;
}

.decoration {
  float: right;
  background-color: white;
  position: relative;
  left: -10px;
  height: 100% // XXX does not work
}
<div class="container">
  <div class="blurb">
    Lorem ipsum...
  </div>
  <div class="decoration">
    ✓
  </div>
</div>

Answers to similar questions recommend using display: table-cell;, but then you have the issue of making the first (text) div stretch horizontally all the way, which is a different can of worms entirely.

Upvotes: 0

Views: 2676

Answers (2)

yinsweet
yinsweet

Reputation: 2851

You can achieve it with position property. The parent container set to relative and child decoration set to absolute with top and bottom set to 0.

.container {
  background-color: lightgray;
  position: relative;
}

.blurb {
  display: inline-block;
  padding: 2em;
}

.decoration {
  float: right;
  background-color: white;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 10px;
  /* Align the content to center */
  display:flex;
  justify-content:center;
  align-items:center;
  text-align: center;
}
<div class="container">
  <div class="blurb">
    Lorem ipsum...
  </div>
  <div class="decoration">
    ✓
  </div>
</div>

Upvotes: 0

Paulie_D
Paulie_D

Reputation: 114990

Flexbox can do that.

.container {
  background-color: lightgray;
  display: flex;
  border: 1px solid red;
  width: 80%;
  margin: 1em auto;
}

.blurb {
  flex: 1;
  padding: 2em;
}

.decoration {
  display: flex;
  align-items: center;
  background-color: white;
  margin-right: 1em;
}
<div class="container">
  <div class="blurb">
    Lorem ipsum...
  </div>
  <div class="decoration">
    ✓
  </div>
</div>

<div class="container">
  <div class="blurb">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Reiciendis molestiae accusantium, magni commodi repellendus quidem facilis doloremque perspiciatis, ab odio omnis deleniti, obcaecati maiores dolores?
  </div>
  <div class="decoration">
    ✓
  </div>
</div>

Upvotes: 3

Related Questions