Why doesn’t the height accept percentage?

Asked

Viewed 2,534 times

8

I created this Fiddle as a test.

Wanting me to have the screen split half green, half red, why is it on the property height I put the value followed by "%" to div disappears? Being here saying you can use "%".

3 answers

8


I believe this solves your problem. The height percentage can only be obtained if it is relative to the other elements that contain these divisions. You have to determine how the upper blocks should behave in relation to the height.

html, 
body  {
    height: 100%;
    margin: 0px;
    padding: 0px;
}

#dv1 {
    width : 100%;
    height : 50%;
    background-color : red;
}

#dv2 {
    width : 100%;
    height : 50%;
    background-color : green;
}
<div id="dv1"></div>
<div id="dv2"></div>

I put in the Github for future reference.

6

When you put a size in percentage, the value is calculated based on the size of the parent element. Keeping this in mind, it is interesting to note that by default, there is no set height on a blank (or even content) site. To see this, use the Inspect element and see in the tag body there is a width, but the height is 0 (it increases according to the content of the site).

To change this, the technique is simply to define a value for the body and the html:

body, html {
    height: 100%;
}

After that, the elements with size in percentage will have their values calculated correctly (previously they were calculated with 0).

4

Height accepts percentage yes.

Look at an example:

#tudo {
  width: 300px;
  height:300px;
}

.bloco-vermelho {
  width: 100%;
  height: 50%;
  background-color: red;
}
.bloco-verde {
  width: 100%;
  height: 50%;
  background-color: green;
}
<div id="tudo">
<div class="bloco-vermelho">
</div>
<div class="bloco-verde">
</div>
  </div>

You can go back to your code and check if there is a semicolon at the end, as it is a common failure when applying CSS.

  • I already realized what the problem was. The problem was that I had given no value to html and body, the div’s "parents"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.