HTML & CSSEasy
What is visibility vs display?
display: none removes an element completely: it takes no space, is not rendered, cannot be focused and is hidden from screen readers. visibility: hidden makes an element invisible but keeps its space in the layout; it is also unfocusable and hidden from assistive technologies. opacity: 0 keeps the element in place and still interactive.
Comparison
display: none | visibility: hidden | opacity: 0 | |
|---|---|---|---|
| Takes space | No | Yes | Yes |
| Clickable / focusable | No | No | Yes |
| Screen readers | Hidden | Hidden | Still read |
| Children can override | No | Yes (visibility: visible) | No |
| Animatable | Discrete only | Yes (discrete step, handy with transitions) | Yes, smoothly |
| Triggers layout change | Yes | No | No |
When to use which
display: none(or thehiddenattribute): content that should not exist right now, like inactive tabs or closed menus.visibility: hidden: hide without shifting surrounding layout; combine with an opacity transition for fades (visibilityswitches at the end of the transition).opacity: 0: fade animations; remember to also make it non-interactive (pointer-events: none,inert).- Visually hidden but readable by screen readers: use an
.sr-onlyutility class (clip-path, 1px size) for things like skip links and labels.
Interview tip
Mention the accessibility differences; they are what interviewers usually look for.
Code example
html
1<style>2 body { font-family: system-ui; }3 .row { display: flex; gap: 8px; margin: 8px 0; }4 .row div { padding: 10px; border: 2px solid #0b1020; background: #dbeafe; }5 .none { display: none; }6 .hidden { visibility: hidden; }7 .transparent { opacity: 0; }8 .sr-only { position: absolute; width: 1px; height: 1px; overflow: hidden; clip-path: inset(50%); white-space: nowrap; }9 .fade { transition: opacity .3s, visibility .3s; }10 .fade.off { opacity: 0; visibility: hidden; }11</style>12<div class="row"><div>A</div><div class="none">B</div><div>C</div></div> <!-- no gap left -->13<div class="row"><div>A</div><div class="hidden">B</div><div>C</div></div> <!-- gap kept -->14<div class="row"><div>A</div><div class="transparent" onclick="alert('Still clickable!')">B</div><div>C</div></div>15<button><span aria-hidden="true">✕</span><span class="sr-only">Close</span></button>16<button onclick="document.getElementById('f').classList.toggle('off')">Toggle fade</button>17<p id="f" class="fade">Fades out, then becomes unfocusable and hidden from screen readers.</p>
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the HTML & CSS set.