Yesterday, I ran into a weird bug in Chrome and Webkit (but not Firefox) using the .visually-hidden class inside an element that had overflow set to anything other than auto.
The visually hidden elements would create a gap at the end of the overflow element, compounding the more of them there were.
I wanted to document the details of the bug, and how I fixed it, because I’m sure I’ll run into this again.
The .visually-hidden class
A .visually-hidden class is used to hide content visually while keeping it accessible to screen readers.
The content cannot be visually seen in the UI (just like [hidden] or display: none), but screen readers can see it and will announce the text (unlike those properties).
It’s a bit of a hack that works by setting the element size to 1px, giving it a negative margin, clipping it, hiding overflow, and moving it outside the viewport.
.visually-hidden {
border: 0;
clip: rect(0 0 0 0);
height: 1px;
margin: -1px;
overflow: hidden;
padding: 0;
position: absolute;
white-space: nowrap;
width: 1px;
}The Bug
If you use the class inside an element with overflow set to scroll, auto, clip, or hidden, the content is clipped as expected, but those 1px high and wide elements “reserve” the space they were in and create a big old gap after the content.
Notice how there’s a big amount of white space after the table? For contrast, here’s that same HTML, but without the .visually-hidden content.
The Fix
I spent so much time hunting this bug down and trying to fix it.
In the end, it was stupid simple: add position: relative to the overflow element.