1

I was trying to create a responsive square and added the following:

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

however, it expands horizontally but vertically does not expand at all...

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width">
  <title>JS Bin</title>
  
  <style>
    body{
      background: #cccede;
      
    }
    

    .square {
  width: 50%;
  height: 50%;
       border: 2px solid black
}
  </style>
</head>
<body>

  <div class="square"></div>

</body>
</html>

In this snippet, why does the box not take the height of the windows to calculate its height?

halfer
  • 19,824
  • 17
  • 99
  • 186
Julio Rodriguez
  • 499
  • 6
  • 16

2 Answers2

1

height: 50% means that it will be half as tall as its parent container. Your square is that small because it's inside the body tag which is small. You can make the body as tall as the screen by doing this:

body {
    height: 100%;
}
Ismael Padilla
  • 5,246
  • 4
  • 23
  • 35
1

As others have said, % works from the container of the element, so you need to manually set a height / width for body.

However, you could also use vh / vw, which are units for a percent of the viewport height, and viewport width respectively

body {
  background: #cccede;
}

.square {
  width: 50vw;
  height: 50vh;
  border: 2px solid black
}
<body>
  <div class="square"></div>
</body>
Shiny
  • 4,945
  • 3
  • 17
  • 33