Hiding Things with CSS
October 04, 2019
There are a handful of ways to hide things using CSS, and each of them has its own strengths and potential drawbacks. Here’s a list of the 5 most common ways to hide content, and a use case or two for each.
display: none; or HTML
- Removes element from visual flow, hiding it from both visual and AT (Assistive Technology) consumption
- Does not transition
- Toggled, closed, or otherwise hidden elements that may be shown again.
- Breakpoint-dependent elements like mobile & desktop menus
Opposite of transparency,
opacity: 1; is fully opaque,
opacity: 0; is fully transparent.
- Does not affect the element’s position in the DOM flow, but a common gotcha here is an
opacityvalue other than
1puts the element in a new stacking context.
opacityapplies to the whole element and any descendants, but is not inherited by the element’s children.
- Temporarily hide elements, typically to fade in after a timeout or on a callback
- Pair with another method to create a smooth transition of content in/out of the visual flow
- Visually hidden, but still occupies the same space in the visual flow.
- Unlike the
visibilityis animatable. Pairs nicely with a short
opacitytransition when animating an element in.
- Hide an element without disrupting the visual flow.
- Pair with DOM manipulation, like
overflow: hidden; height: 0;to enable transitions where
display: none;would fall short.
- Hides from screen readers, but not visually.
- Visual-only elements that already have descriptive text
- Redundant elements (all but one of mobile/tablet/desktop menus)
Hides visually, but not to AT. A11y guidelines on this are an excellent description.
- Visually redundant elements already described in the DOM
- Input labels made redundant by a visual overhaul using pseudo-elements
Things to Remember
- All content hidden with CSS will become visible if styles are disabled.
- Be careful not to hide the full functionality of your site from screen reader and/or keyboard-only users.