Sub topic 3
`display: none`
Assume you know basic HTML, CSS selectors, and the CSS box model. The display property controls the box an element generates and how that box participates in layout. display: none generates no box:
.panel.is-closed {
display: none;
}The element is removed from layout. It takes no space, and following content moves into its place. Changing the value back to block, inline, or another value displays it again.
Comparing hiding methods
| Rule | Takes layout space | Visible | Receives normal focus |
|---|---|---|---|
| `display: none` | No | No | No |
| `visibility: hidden` | Yes | No | Usually no |
| `opacity: 0` | Yes | No | Yes |
visibility: hidden keeps the element's layout space but makes it invisible. opacity: 0 makes the element transparent while it still participates in layout and can still receive pointer events and keyboard focus.
Hidden content, focus, and assistive technology
Content with display: none is generally excluded from the accessibility tree, so screen readers do not announce it. Its descendants cannot be reached by normal keyboard focus.
When hiding an interactive component, also manage its state. Remove focus from controls that become hidden, and update an accessible state such as aria-expanded on the control that opens the component. opacity: 0 needs extra care because an invisible control may remain keyboard- or pointer-accessible.
Choosing a display value
- Use
noneto remove an element and its space from layout. - Use
blockwhen an item should start on a new line. - Use
inlinefor text-level content that should flow within a line. - Use
inline-blockfor inline-flow items that need width, height, or box spacing.
Modern display values
Use flex for one-dimensional alignment and distribution, and grid for rows and columns. Use flow-root to create an independent block formatting context, often to contain floats. Use contents when an element's own box should disappear while its children participate in the parent's layout. Test contents carefully because its accessibility behavior depends on the browser and element.
Exercise
A closed navigation panel must stop taking space and must not leave its links keyboard-focusable. Which value should you use?
Show answer
Use display: none, and keep the controlling button's accessible state synchronized with the panel's open or closed state.