Niccolò Guidi
Niccolò Guidi

Reputation: 195

Resizing of a div in an other div on resizing of the page

I would like to resize my div that is in another div that has to be more little than the master div.

I wrote this jsfiddle to make you understand.

Jsfiddle

Jsfiddle whit div.resize in % height

HTML:

<div class="container">
 <div class="resize">
  <div class="red">
  </div>
 </div>
</div>

CSS:

.container
{
    width:800px;
    height:500px;
}
html,body{
    height:100%;
    width:100%
}
.resize{
  height:200px;
}

.red{
background-color: red;
height: 50%;
}

I can't understand why, if I resize the page and also the div "resize", the div "red" doesn't resize.

Upvotes: 0

Views: 112

Answers (1)

Scott Marcus
Scott Marcus

Reputation: 65808

It is working just fine. Added some outlines so you can see the edges.

The .red div is half the height of its parent. Change the parent and you'll see the .red div change its height.

Also, resizing the browser window should not have any effect, since you are setting the .container and the .resize to fixed pixel values.

html,body{
    height:100%;
    width:100% /* Not needed, this is the default */
}

.container {
  width:600px;
  height:150px;
  outline:1px solid black;
}

.resize{
  height:100px;
  outline:1px solid aqua;
}

div.red{
  background-color: red; 
  height: 50%;
}
<div class="container">
 <div class="resize">
  <div class="red"></div>
 </div>
</div>

But, if you are looking for automatic resizing, you can't use fixed values (pixels), you must use relative values (percents, vh, vw, em), like this:

.container {
  width:600px;
  height:10vh; /* 10% the height of the viewport */
  outline:1px solid black;
}

.resize{
  height:75%; /* 75% the height of the parent element */
  outline:1px solid aqua;
}

div.red{
  background-color: red; 
  height: 50%; /* 50% the height of the parent */
}
<div class="container">
 <div class="resize">
  <div class="red"></div>
 </div>
</div>

Upvotes: 1

Related Questions