Problem

You designed a web page and a particular element needs to appear only when the user visits the page from their Desktop. If the user visits the page from a smaller device, like a mobile or tablet, the element needs to be hidden.

Solution

CSS has a feature called media rules. Media rules allow us to accomplish this task. We can use a rule that specify how wide the screen is and apply some CSS based on that logic. For this example, a small screen with width of 600px will act as a device to hide the item.

So the code will be as follows:

@media only screen and (max-width: 600px) {
    /*you CSS here*/
}

The code above says to the web browser to check the media (device) and if it’s screen and the width less than 600px, then apply the CSS rules enclosed by the curly brackets. A good approach to test that is working is to change the background color.

Let’s add the CSS to change background color to yellow.

@media only screen and (max-width: 600px) {
    body {
        background-color: yellow;
    }
}

Let’s suppose an empty HTML file as follows:

<html>
	<head>
		<style>
		    @media only screen and (max-width: 600px) {
				body {
					background-color: yellow;
				}
			}
		</style>
	</head>
	<body>

	</body>
</html>

Now, if I open that to the a web browser I would expect to have the background page to white at the beginning when the window is full size. While I resize the page to shrink, less than 600px then the yellow should be applied.

We can see when the window resizes and gets smaller than 600px, the background color changes. Now, let’s add an item to the body and hide it when the window resizes.

For example, let’s add a header message to the <body>.

<body>
    <h1>This will disappear when screen < 600px<h1>
</body>

Let’s update the media rule to hide the header element.

h1 {
    display: none;
}

The complete code looks as follows:

<html>
	<head>
		<style>
		    @media only screen and (max-width: 600px) {
				body {
					background-color: yellow;
				}
				h1 {
					display: none;
				}
			}
		</style>
	</head>
	<body>
		<h1>This will disappear when screen < 600px<h1>
	</body>
</html>

Let’s open it in the web browser and resize it once again:

It works

Conclusion

In this post we saw how to apply CSS media rules and hide an element when a screen has less than 600px width. Check out other posts in CSS. You can download the example file below.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x