saf21
saf21

Reputation: 844

How to make div height 100% inside relative div?

This is my code:

<div class="parent">
  <div class="child-1"> CHILDREN 1 </div>
  <div class="child-2"> CHILDREN 2 </div>
  <div class="child-3"> CHILDREN 3 </div>
</div>

CSS:

.parent {
  position: relative;
  height: 250px;
}
.child-1 {
  position: absolute;
  top: 0;
  width: 100%;
}
.child-2 {
  height: 100%;
}
.child-3 {
  position: absolute;
  bottom: 0;
  width: 100%;
}

I set child-2 as 100% but didn't happen. So, how to make .child-2 height 100% and between child-1 and child-3?

Upvotes: 2

Views: 7613

Answers (4)

Domain
Domain

Reputation: 11808

Add your child-2 below css:

.child-2 {
height: 100%;
position: absolute;
top: 50%;
bottom: 50%;
}

And your child-3 class top 100%:

.child-3 {
position: absolute;
bottom: 0;
width: 100%;
top: 100%;
}

child-2 will become at the middle of the other two divs.

Upvotes: 0

Alin P.
Alin P.

Reputation: 44346

Assuming I understood correctly what you want to do... This seems like a job for Captain FlexBox®.

.parent {
  display: flex;
  flex-direction: column;
  
  width: 300px;
  height: 200px;
  background: Yellow;
}
.child-1 {
  background: Red;
}
.child-2 {
  flex-grow: 1;
  
  background: Green;
}
.child-3 {
  background: Blue;
}
<div class="parent">
  <div class="child-1"> CHILDREN 1 </div>
  <div class="child-2"> CHILDREN 2 </div>
  <div class="child-3"> CHILDREN 3 </div>
</div>

The important parts are setting display: flex on the container, instructing the rendering engine to calculate by the flex rules, changing the direction to vertical with flex-direction: column and making only the middle child fill up all the remaining space with flex-grow: 1.

Upvotes: 4

Dilshan Perera
Dilshan Perera

Reputation: 132

You can use display:table-cell property for this

Upvotes: 0

Radu Lozovanu
Radu Lozovanu

Reputation: 167

Maybe if you delete the position: absolute; from your .child you will get that you want, cause in your case you get the .child-2 on the top of .child-1 div.

Try this:

.parent {
  position: relative;
  height: 250px;
}
.child-1 {
  top: 0;
  width: 100%;
}
.child-2 {
  height: 100%;
}
.child-3 {
  bottom: 0;
  width: 100%;
}

Upvotes: 0

Related Questions