0

I want to have a div scale relative to the size of my window, whether that be because I am on mobile or I scale the browser. However when I try to set the size of my div to something like

div {
  width: 80%;
  height: 50%;
  background-color: grey;
}

It doesn't work. I have read around and it seems that I need to define a reference div, but that wouldn't make this div scale to the screen. I think the <meta> tag would fix things, but I am using codepen.io for this project and I don't know if I can include that since the only html they ask for is anything in the body.

2 Answers2

2

The % unit is relative to the parent element, not the viewport. If you'd like to set the dimensions of an element relative to the size of the viewport, you can use the vw (viewport width) and vh (viewport height) units. These work similar to percentage-based units (1vw is 1% of the viewport width).

div {
  width: 80vw;
  height: 50vh;
  background-color: grey;
}
coreyward
  • 77,547
  • 20
  • 137
  • 166
0

You will need to set the height for the parent element because height: 80% is relative to the height of the parent. Try this:

html {
  height: 100%;
}
body {
  height: 100%;
}
#test {
  background: #ff0000;
  height: 80%;
  width: 50%;
}
<div id="test"></div>
ajarrow
  • 414
  • 2
  • 10