David
David

Reputation: 825

Why does this container expand beyond the viewport?

I have a container that contains 4 colored blocks. I have styled the container to be 27px from the top of the viewport, and 2% from the left (this works). However, I want the right and bottom sides of this container to stop at the viewport, but instead it is going beyond it.

The blocks in the example below are thus slightly out of the viewport.

What am I doing wrong?

Please note that in the code below, the top row is almost 30 pixels higher than the bottom row because the container is not within the viewport completely.

I have a feeling it has to do with the wrapper container itself, specifically with the height and width as it is taking account of the margins that I gave it while still having a 100% height and width, but I am not sure.

Edit : When running the code below, it should be obvious there is a problem since the blocks are not all equal size due to the wrapper overflow.

body {
  margin:0;
  padding:0;
  overflow: hidden;
  
}


#wrapper {
  position: relative;
  width: 100vw;
  height: 100vh;
  margin-top: 27px;
  margin-left: 2%;
}

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

#square1 {
  top: 50%;
  left: 0;      
  background-color: blue;
}

#square2 {
  top: 50%;
  left: 50%;      
  background-color: yellow;
}

#square3 {
  top: 0;
  left: 0;      
  background-color: green;
}

#square4 {
  top: 0;
  left: 50%;      
  background-color: red;
}
<div id="wrapper">
  <div id='square1' class="square"></div>
  <div id='square2' class="square"></div>
  <div id='square3' class="square"></div>
  <div id='square4' class="square"></div>
</div>

Upvotes: 0

Views: 1189

Answers (2)

Johannes
Johannes

Reputation: 67778

The margins are added to width and heigth properties, so 100vh height plus a margin of 27px will result in the bottom of the element being 27px below the viewport bottom. To avoid this, you can use height: calc(100vh - 27px).

Upvotes: 2

Dan Knights
Dan Knights

Reputation: 8368

You can use calc to account for the margin:

body {
  margin:0;
  padding:0;  
}


#wrapper {
  position: relative;
  width: calc(100vw - 2%);
  height: calc(100vh - 27px);
  margin-top: 27px;
  margin-left: 2%;
}

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

#square1 {
  top: 50%;
  left: 0;
  
  background-color: blue;
}

#square2 {
  top: 50%;
  left: 50%;
  
  background-color: yellow;
}

#square3 {
  top: 0;
  left: 0;
  
  background-color: green;
}

#square4 {
  top: 0;
  left: 50%;
  
  background-color: red;
}
<div id="wrapper">
  <div id='square1' class="square"></div>
  <div id='square2' class="square"></div>
  <div id='square3' class="square"></div>
  <div id='square4' class="square"></div>
</div>

Upvotes: 2

Related Questions