Home > other >  How to make child's height the same as parent
How to make child's height the same as parent

Time:07-18

In my application I have a parent div and two other child divs inside this parent. One of these child div's has a set height while the other does not. I want to make the div who does not have a set height to be the same as the parent.

An illustration of what I am referring to can be seen in this jsfiddle: https://jsfiddle.net/ll3333/2Lxuj8wk/10/.

In this example, I want the div with class "child-2" to be the same height as the parent. For some reason, setting its height to "100%" does not seem to be working.

Thanks!

CodePudding user response:

From the MDN on height:

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to auto. A percentage height on the root element is relative to the initial containing block.

The 100% of the height property that you are setting is telling the element to take up 100% of the parent's height (and this chains all the way to the first absolutely-specified height). However, you never actually specify the height of the parent element itself.

To resolve this, you'll need to set a height of 300px on the parent. Note that this means that the other element could also make use of height: 100%, which would allow you to save on code (though this is not shown below).

.parent {
  display: flex;
  flex-direction: row;
  border: 1px solid purple;
  height: 300px;
}

.child-1 {
  height: 300px;
  background-color: blue;
  width: 40px;
}

.child-2 {
  height: 100%;
  background-color: red;
  width: 40px;
}
<div >
  <div >
  </div>
  <div >
  </div>
</div>

CodePudding user response:

you can add align-items: stretch; for .parent and remove height: 100%; in .child-2

.parent {
  display: flex;
  align-items: stretch;
  flex-direction: row;
  border: 1px solid purple;
}

.child-1 {
  height: 300px;
  background-color: blue;
  width: 40px;
}

.child-2 {
  background-color: red;
  width: 40px;
}
<div >
  <div >
  </div>
  <div >
  </div>
</div>

  • Related