Home > Back-end >  Why is the body overflow property ignored if I add overflow-x: hidden to the html tag?
Why is the body overflow property ignored if I add overflow-x: hidden to the html tag?

Time:11-17

I had an issue with body overflow being ignored and playing around I found out it happens because someone did:

html{
overflow-x: hidden;
}

I would never do this because styling the html element directly seems like a sauvage act to me. But since someone did, I want to understand this situation:

html{
overflow-x: hidden;
}

body{
overflow: hidden;
}

.fill{
height: 8000px;
border: 1px solid blue;
}
<html>
<body>
<div ></div>
</body>
</html>

Run it an note that the body overflows normal, hidden is ignored.

Of course, If I remove the overflow property from the html selector, it works as expected.

CodePudding user response:

As stated in this W3 documentation about overflow:

UAs must apply the 'overflow' property set on the root element to the viewport. When the root element is an HTML "HTML" element or an XHTML "html" element, and that element has an HTML "BODY" element or an XHTML "body" element as a child, user agents must instead apply the 'overflow' property from the first such child element to the viewport, if the value on the root element is 'visible'.

So, long story short, I don't think it is possible to make the body overflow property work when the HTML element has an overflow. As this is not the correct usage of said css property.

CodePudding user response:

There is no overflow inside the body element because its height is defined by its content. If you want overflow: hidden to work you need to fix a height and that height need to be smaller than the height of the screen (the viewport) to not trigger the overflow of the viewport.

html {
  overflow-x: hidden;
}

body {
  overflow: hidden;
  height: 80vh; /* a fixed height */
  /* or 100vh for full screen and don't forget margin:0 */
}

.fill {
  height: 8000px;
  border: 1px solid blue;
}
<html>

<body>
  <div ></div>
</body>

</html>

When you remove overflow-x: hidden you are facing another situation where the overflow of the body is getting propagated to the root element then to the viewport. Still the content inside the body is not overflowing but the whole body is overflowing and this overflow is hidden due to the propagation.

  • Related