Sometimes certain parts of a website only work on a certain platform. Mobile deep links are a good example of this; certain deep links can’t be handled on desktop.

Use this CSS technique to hide Document Object Model (DOM) elements from the user based on whether they are on mobile or desktop.

Technique

I prefer a non-javascript solution when possible so the end user doesn’t need javascript enabled1. Why use a dynamic solution when a static one will do? This can be accomplished with CSS.

The idea is to use CSS media queries to determine which platform we are on and then hide elements accordingly using the display property. The elements will still be loaded by the user but will not be displayed to them on screen.

For this article I’ll assume that the largest mobile device screen width is 600 pixels.

Mobile Only DOM Elements

Let’s make a CSS class that will only display on mobile devices called mobile-only. We need to set display: none on desktop. We are not on mobile if the screen size is greater than our maximum mobile screen size (600 pixels). This implies the minimum screen width considered not mobile (ie. desktop) is 1 pixel greater; in our case 601 pixels.

@media screen and (min-width: 601px) {
  .mobile-only {
    display: none !important;
  }
}

display: none hides the element from view. !important makes the display setting override all previous styling rules. The media query applies the rule to any screen that isn’t what we consider a mobile device.

Note that !important is important here because whether an element should be displayed or not is the most important thing to consider when rendering the page.

Now you can add mobile-only to the class attribute of an element to have it only appear on mobile.

Desktop Only DOM Elements

This is similar to the mobile elements. We need to set display: none on mobile. We can just do a simple media query for mobile devices using max-width.

@media screen and (max-width: 600px) {
  .desktop-only {
    display: none !important;
  }
}

Add desktop-only to the class attribute of an element to have it only appear on desktop.

Cleaner Implementation

If you have SASS/SCSS available in your tech stack, you can use mixins and variables to create a cleaner implementation:

// Max screen width of devices
$on-palm: 600px !default; // mobile/handheld

@mixin media-query($device) {
  @media screen and (max-width: $device) {
    @content;
  }
}

// Complement of media-query.
@mixin media-query-not($device) {
  @media screen and (min-width: $device + 1) {
    @content;
  }
}

@include media-query-not($on-palm) {
  .mobile-only {
    display: none !important;
  }
}

@include media-query($on-palm) {
  .desktop-only {
    display: none !important;
  }
}
  1. I use the NoScript Security Suite. New scripts are blocked by default.