Here is the code:
body {
margin: 0;
padding: 0;
}
div {
-webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
-moz-box-sizing: border-box; /* Firefox, other Gecko */
box-sizing: border-box;
}
.body {
width: 100vw;
height: 100vh;
background-color: black;
padding-top: 20vh;
}
.content {
width: 50vw;
height: 1000px;
background-color: yellow;
}
<body>
<div class="body">
<div class="content">
</div>
</div>
</body>
The problem is fairly simple. When I add padding-top to the .body div, there is a horizontal overflow. I would like to know why does the y-axis padding affect the x-axis width.
I know I can get rid of it using overflow-x: hidden, but it’s a dirty solution.
4
Answers
why adding padding to the .body div causes a horizontal overflow is because of the default behavior of the CSS box-sizing property
Just use a percentage value:
Reference: What’s The Difference Between PX, EM, REM, %, VW, and VH?
The answer to this issue is quite simple & the culprit is y-axis scrollbar.
Lets first undertands how viewports works . Viewport units looks at the window rather than the content on the page. So when you were trying to render a width of 50vw it actally rendered the viewport not including the scrollbar width in it . The reason you see scrollbar in x-axis is due this reason. In simple words the scrollbar width is not included ( y-axis one ) when calculating the width of the element hence there’s a overflow issue.
To bypass this behaviour you can use the overflow overlay. Which makes scrollbar floats over the content ( overlays y-axis scrollbar )
For understanding overflow overlay checkout this article
If you’re trying to set up the page with a header (as your comment suggests) then why not use flexbox to guide you, and semantic elements.
Set the body as a flex column element. Add a
header
element to that at20vh
, and then add amain
element with your content.