CSS Display & Visibility: Controlling the Canvas
The browser canvas is a grid of boxes. Knowing how to manipulate these boxes—whether they stack, sit side-by-side, or disappear completely—is the foundation of all CSS Layout.
The Great Vanishing Act: None vs Hidden
One of the most common layout requirements is hiding an element. But there are two very different ways to do this, and mixing them up will break your design.
1. display: none;
This completely removes the element from the document flow. It's as if the element was deleted from your HTML. Other elements will close the gap and take its place.
2. visibility: hidden;
This makes the element visually disappear (it becomes transparent and cannot be clicked), but it maintains its physical dimensions. It leaves a "ghost" hole in your layout where it used to be.
Building Blocks: Block vs Inline
Every HTML element has a default display value. The two fundamental ones are block and inline.
- Block: Elements like
<div>,<p>, and<h1>. They always start on a new line and stretch to take up 100% of the available width of their container. - Inline: Elements like
<span>,<a>, and<strong>. They sit side-by-side like text. Crucially: you cannot applywidthorheightto an inline element.
The Hybrid: Inline-Block
What if you want elements to sit side-by-side (like inline), but you still want to explicitly set their width, height, margins, and padding (like block)?
Enter display: inline-block;. It gives you the best of both worlds and was the primary way of making grid systems before Flexbox and CSS Grid came along.
Accessibility (a11y) Considerations+
Screen Readers care about how you hide things. Both display: none and visibility: hidden will hide content from screen readers. If you want to visually hide an element but keep it readable for screen readers (like a custom label), use a "visually-hidden" CSS class that clips the element using positioning, rather than removing it from the display tree entirely!
❓ Frequently Asked Questions
What is the difference between opacity: 0 and visibility: hidden?
Opacity: 0 makes the element transparent, but it still occupies space and can still receive clicks and mouse events!
Visibility: hidden makes the element invisible and it still occupies space, but it can NO longer receive clicks.
Why is my margin-top not working on my span?
span elements have display: inline by default. Vertical box properties (height, margin-top, margin-bottom) do not affect inline elements to avoid breaking the text line-height. Change the element to display: inline-block or display: block.
Can I animate "display: none"?
No. CSS transitions require numerical values or intermediate states. There is no middle ground between "block" and "none." If you need to animate an element disappearing, you must animate its opacity and then use JavaScript or advanced hacks to apply display: none once the transition ends.
