How do I stop css grid width extending beyond screen width, and how do browsers calculate css-grid width?

Viewed 3101

I have the following:

<html>
<head>
<style>
  #outer-grid {
    display: grid;
    grid-gap:0vh;
    grid-template-columns: repeat(2, 1fr) 30px;     /*also tried auto in place of 1fr*/
    grid-template-rows: repeat(2,1fr);
    height: 100vh;
    width: 100vw;
    position: absolute;

  }
</style>
</head>
<body>
<div id='outer-grid'>
  <div>item 1</div>
  <div>item 2</div>
  <div>item 3</div>
  <div>item 4</div>
  <div>item 5</div>
  <div>item 6</div>
</div>
</body>
</html>

This results in content extending beyond the screen width, with scroll bars added (Firefox). What I was expecting is for the right hand column to be fixed at the right hand margin. What am I doing wrong?

How does the browser calculate the overall width in this case?

2 Answers

So, what's happening is that you are giving your grid 100vw, meaning, it will be 100% of the width of the viewport right? Well, by default, the body has margin around, so, your grid will be 100vw but because you have margin in the body, the grid seems to go off screen.

So, what you need to do, to reset the layout is:

*{
  margin:0;
  padding: 0;
}

And then, just apply the margins and paddings you want in the grid element.

You could probably follow something along the lines of the codepen, that I've created: https://codepen.io/pedro-figueiredo/pen/EBaGOg

Try this

<meta name="viewport" content="width=device-width, initial-scale=1.0">

Refer this for responsive design

Related