Zebrafish
Zebrafish

Reputation: 13878

Why isn't my CSS style changing the attribute height here?

If I set width of the "div" element to % it works fine, but if I set the height to a % I get nothing. Only if I specify the height in px or em or something does it work:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
  </head>
    <style>
        div {
            background-color: aqua;
            height: 25%;
            width: 25%;
             float: left; 
            }
    </style>

<body>
   <div></div>
</body>
</html>

This is confusing me. Thanks.

Upvotes: 1

Views: 70

Answers (2)

Emad Fani
Emad Fani

Reputation: 445

the dive will get 25% of its parent height and width so if you didn't style body to have an special height or width it most be 0px in you'r case add some height to body and it will get styled

body {
 height:100%;
 padding:0;
 margin:0;
}

Upvotes: 2

kyun
kyun

Reputation: 10264

<style>
    body{
       height: 100vh;
       width: 100vw;
    }
    div {
        background-color: aqua;
        height: 25%;
        width: 25%;
         float: left; 
        }
</style>

When you set width or height with %, You have to check it's parent tag.

For example,

.parent{
  width: 200px;
  height: 200px;
 }

.children{
  width: 50%;
  height: 50%;
}

.children 's height and width is 100px.

Let's see another exmaple.

.parent{

}
.children{
  width: 50%;
  height: 50%;
}

.children's height and width is 0px.

because it's parent doesn't have width and height.

Upvotes: 2

Related Questions