Hiding and Showing HTML Elements

Sometimes a responsive layout requires completely removing certain elements on small screens. You can hide or show elements based on screen size by combining CSS media queries with the display property.

For example, a large sidebar full of advertisements might look fine on a desktop monitor, but it will take up too much valuable space on a mobile phone. Conversely, a compact "hamburger" menu icon is necessary on a phone, but pointless on a desktop where there's plenty of room for a full text menu.

Using display: none;

To hide an element, we set its display property to none. This completely removes the element from the document flow, meaning it takes up zero space, almost as if it were deleted from the HTML entirely.

To show an element that was previously hidden, we change its display property to a visible state, such as block or flex.

The Mobile-First Approach

When hiding and showing elements, web developers often use a "mobile-first" approach. This means the default CSS is written for mobile phones, and media queries are used to add complexity for larger screens.

Something like this:

The Desktop-First Approach

Alternatively, you can write the default CSS for desktop computers and use media queries to hide elements when the screen gets too small:

Full Working Example

The following example uses the desktop-first approach to swap a full navigation menu for a compact mobile icon. Try resizing your browser window past the 600px breakpoint to watch the text menu disappear and the icon appear:

View Output Full Screen Preview

Tip: Using Visibility Instead

If you want to hide an element but keep the empty space it occupies (so your layout doesn't shift), use visibility: hidden; instead of display: none;.