Hiding and showing
Learn to hide elements responsively with display: none.
Hiding elements with display: none
The display: none declaration removes an element from the page layout entirely. It takes no space, is not seen by accessibility tools, and can't be clicked. Combine it with a media query to show elements only on narrow or wide screens.
This is the most common hiding method in responsive design. It's ideal for hiding a side menu on mobile, or the hamburger button that only makes sense on mobile, on the desktop view.
Hiding on narrow screens
To hide an element on narrow screens, write display: none in the base styles and bring it back with display: block inside an @media (min-width: 768px) block. This matches the mobile-first approach: less HTML shows on mobile, more items open up on desktop.
For example, a magazine side menu can stay hidden on mobile and open on desktop.
Show on mobile, hide on desktop
The reverse is also common: a hamburger menu button should appear only on narrow screens. Write .menu-toggle { display: block; } in the base styles and display: none inside @media (min-width: 768px).
The button shows on mobile and takes no space on desktop. In a mobile-first layout the base value always reflects the mobile view.
Exercise Show the menu button only on desktop
In a mobile-first layout, the .menu-toggle button should stay hidden on mobile and come back at 768 pixels and up. Write display: none in the base styles and display: block inside an @media (min-width: 768px) block.
Show example solution
.menu-toggle {
display: none;
}
@media (min-width: 768px) {
.menu-toggle {
display: block;
}
}
Test yourself
-
What is the difference between display: none and visibility: hidden?
.a { display: none; } .b { visibility: hidden; }- They are the same
- visibility is faster
- display takes no space, visibility keeps space
- display only works for print
Show answer
display takes no space, visibility keeps space — Correct. display: none removes the element; visibility: hidden keeps its space but makes it invisible.
-
Hide the side menu on mobile
.sidebar { display: ____; } @media (min-width: 768px) { .sidebar { display: block; } }Show answer
.sidebar { display: none; } @media (min-width: 768px) { .sidebar { display: block; } } -
Match each scenario to the right declaration
- Hide on narrow screen
- display: none
- Show on wide screen
- display: block
- Print only
- @media print
- Keep space, invisible
- visibility: hidden