Published at
Updated at
Reading time
2min
This post is part of my Today I learned series in which I share all my web development learnings.

Responsive design can be a real challenge if you're coding something that needs more than just squishing and reordering some boxes. Scott O'Hara published an article describing how to build elements that act as buttons or spans depending on the viewport size.

The trick: Scott uses CSS visibility to hide and show elements throughout the element tree conditionally.

<!-- Hide the button on smaller viewports 
     and only show the span -->
<button type="button">
  <span>Do something</spin>
</button>

Wait what? As it turns out, nested elements with different visibility properties (visible / hidden) can be visible even though their parent is hidden. 😲

Here's the MDN section about this topic.

Descendants of the element will be visible if they have visibility set to visible.

That's pretty wild!

Playground
Choose the CSS property to toggle
Preview
display: block
display: block
display: block
There are no surprises when using display.

Elements with display: none and all its descendants are hidden and don't take up any space.

I'm not sure yet, what to make of this discovery. Other CSS properties such as color or background obviously have the same behavior, sure, wy shouldn't an element have a different background color than its parent element. But for visibility (or as folks pointed out, pointer-events) this behavior seems off.

And then there are CSS properties such as text-decoration where I'd totally expect that you can overwrite the ascendant's CSS, but you can't. 😲

HTML
CSS
Preview

Regarding Scott's responsive pattern, it's incredibly smart but also feels super hacky. I'll have to sleep over all these discoveries...

If you enjoyed this article...

Join 5.5k readers and learn something new every week with Web Weekly.

Web Weekly — Your friendly Web Dev newsletter
Reply to this post and share your thoughts via good old email.
Stefan standing in the park in front of a green background

About Stefan Judis

Frontend nerd with over ten years of experience, freelance dev, "Today I Learned" blogger, conference speaker, and Open Source maintainer.

Related Topics

Related Articles