Encodera

Thanks for reading!

Donate to the site — we work hard for you.

How to show an element only on mobile or only on desktop

Short answer

Hide the element by default and show it in a media query for narrow screens. Change the window width:

<style>
  .mobile-only { display: none; }
  @media (max-width: 600px) {
    .mobile-only { display: block; }
    .desktop-only { display: none; }
  }
</style>
 
<p class="mobile-only">📱 You are on a narrow screen</p>
<p class="desktop-only">🖥 You are on a wide screen</p>

By input type, not by width

A narrow window happens on a computer too, and a tablet has a wide screen. If what matters is whether there is a mouse, check that directly:

<style>
  .touch-hint { display: none; }
  @media (hover: none) and (pointer: coarse) { .touch-hint { display: block; } }
</style>
 
<p class="touch-hint">Swipe left to see more</p>
<p>The hint above is shown only on touch screens.</p>

The container width

If a block should change depending on where it stands rather than on the window, use @container container queries — a card in a narrow sidebar and in a wide main column will look different.

Common mistake

The same content is written twice — a phone version and a desktop version — and the extra one is hidden. The page gets heavier, search engines see duplicates, and when editing it is easy to update the text in only one copy. Try to rearrange one block with CSS layout, and hide only truly different elements, such as a menu button.

Functions used in this recipe

  • @media — Applies rules only under given conditions — the window width, the system theme and others.
  • display — Decides how an element behaves in the flow and how it lays out its content.
  • @container — Applies rules depending on the size of a container rather than the window.

Thanks for reading!

Donate to the site — we work hard for you.