🔵 CSS Q11 / 21

What is the difference between display: none and visibility: hidden?

AI-Powered Answer ✓ Answered

Both `display: none` and `visibility: hidden` are CSS properties used to hide elements on a webpage. While they both achieve the goal of making an element invisible to the user, they do so in fundamentally different ways that impact the document layout, accessibility, and interactivity.

display: none

When an element has display: none applied, it is completely removed from the document flow. This means the browser behaves as if the element does not exist at all on the page. It will not occupy any space, and other elements will reflow to fill the void left by the hidden element. This property is often used when you want to dynamically add or remove elements from the layout entirely.

css
.my-element {
  display: none;
}

visibility: hidden

In contrast, visibility: hidden hides an element but keeps it in the document flow. The element still occupies its original space on the page, and the layout of other elements remains unchanged. The element is simply rendered transparent, becoming invisible. This property is useful when you want to hide an element temporarily without altering the page layout, such as in certain animation sequences or when reserving space for future content.

css
.my-element {
  visibility: hidden;
}

Key Differences Summarized

Featuredisplay: nonevisibility: hidden
Space OccupancyDoes not occupy any space in the layout.Occupies its original space in the layout.
Document FlowRemoved entirely from the document flow.Remains in the document flow.
Layout ImpactCauses other elements to reflow and fill its space.Does not affect the layout of other elements.
Child ElementsCompletely hides all child elements; cannot be overridden by children.Hides child elements, but children can be made visible by setting `visibility: visible`.
Event HandlingCannot receive user interactions (clicks, focus, etc.).Cannot receive user interactions (clicks, focus, etc.), despite occupying space.
Screen Reader AccessibilityGenerally not accessible to screen readers.Generally accessible to screen readers (content is read aloud).
CSS Transitions/AnimationsCannot be animated or transitioned smoothly directly (e.g., animating `display` property).Can be animated or transitioned (e.g., combined with `opacity` or using `transition: visibility 0s 0.5s, opacity 0.5s`).