Using a Media Query to Selectivly Display Content

Example

Carefully examine this screen using a desktop. Now try a cellphone. Do you notice a difference?

You're viewing this page on a mobile device such as a cell phone.

You're viewing this page on a desktop or other device with a larger viewport.

Code

HTML

    <p class="mobileonly">You're viewing this page on a mobile device such as a cell phone.</p>
    <p class="desktoponly">You're viewing this page on a desktop or other device with a larger viewport.</p>

CSS


/* create the mobile only  class */

.mobileonly {display: none;}

@media screen and (max-width: 599px) {
	.mobileonly {display: inline-block;
	background-color: red;}
}


/* create the desktop only class */

.desktoponly {display: none;}

@media screen and (min-width: 600px) {
	.desktoponly {display: inline-block;
	background-color: yellow;}
}



An Explanation

This is a simple switch. All of the text is downloaded; however, the two different classes are used to hide or display the desired text. If the viewport is small, the mobile only text becomes visible while the desktop only text is hidden. If the viewport is large, the mobile only text is hidden while the desktop only text becomes visible.