Supporting different screen sizes through CSS4 Media Queries

Ever wondered how professional websites look exactly as they are meant to look in devices of different screen sizes?

In this fast-paced age of technology, web browser enabled devices often come with different screen sizes. For instance, a tablet might have double the size of a screen in a smart phone. Similarly, PC’s LCDs would have larger screen sizes and resolutions. When the web browsers initially came to existence, there was hardly any issues or concern regarding the screen sizes, as most PCs were pretty much compliant to the standard resolution. Now, the time has changed, and so the screen sizes.

It should be noted that HTML provides the actual layout of a page, which is rendered on our browser, while CSS provides the theme or stylizing of your page. As screen size is related mostly to the style of a page, rather than the actual content, it makes perfect sense for the issue to be resolved through CSS rather than HTML.

Worry not, as CSS3 standard supports Media Queries (by using @media rule), through which multiple screen sizes can be supported by changing the CSS code conditionally, and thus different sections of your HTML page can be tailored based on the screen sizes.

Now, before moving into the actual real-world examples, let’s first discuss the hype behind these Media Queries.

CSS Media Queries

So, what really are those Media Queries? It’s a feature in CSS3, which was previously known as “media types”. In CSS2, we could only specify stylesheets for specific media types such as screen or print. Now with ‘media queries’ in CSS3, we are able to target specific screen sizes.

It supports conditional CSS code based on the characteristics of a device which is rendering the content . So, for instance, if the device has a minimum width of 720px resolution (as commonly seen in modern PCs), the section of your HTML code using aforementioned CSS Media Queries will affect only if it is being rendered in that specific device! Without the support of Media Queries, we had to write multiple HTML pages to cater the different screen sizes.

If you have a background in C programming language, note that it’s procedural based programming supported a feature, called “C Macros” through which we could compile conditional code based on the architecture. In that sense, Media Queries are “Macros” for HTML which is provided by CSS.

Now, let’s see how we can actually implement CSS Media Queries instead of studying the boring theories. Following is the simplest usage of this feature:

@media (max-width: 300px) {
 body {
            background-color: red;
      }
 }

Here, @media is used to denote the Media Queries. We define the CSS code for the devices whose “max-width” is 300px, which points to many mobile devices. The “background-color” of the body section would be “red” if the page is rendered on those devices.

As we only want our CSS code to affect the screen sizes, we could also do the following:

@media screen and (max-width: 300px) {
 body {
        background-color: red;
      }
 }

We use “and” to require multiple queries to be true, and the comma, “,” as an “or” operator for either of the two queries to be true. “all” is used to suggest that it should apply to all the devices. “screen” is used to suggest that it must be a computer screen.

Not only screen sizes (i.e., resolutions), it can also detect many things on a device, such as, width, height, orientation, etc.

We can abstract the generic CSS syntax from our examples:

@media not|only mediatype and (media feature) {
     code;
 }

Apart from using different CSS code for different devices, you can even call the CSS file conditionally!

Here, we the browser will only load “medium.css” if the screen has the “min-width” of 720px AND “max-width” of 900px.

Example

Let’s use CSS Media Queries for real-world example. Suppose, you have a blog, in which you have sidebars on the right side, and the content in the middle. As devices with small screen sizes wouldn’t be able to tolerate sidebars along with the content, you have to show content only in smaller screen sizes, and the sidebars should be below the content.

We would define a class, called “sidebar” which will have the styling of our right sidebar.

.sidebar {
 font-size: 20px;
 max-width: 50%;
 margin-right: 50px;
 }
.sidebar h3 {
 font-size: 30px;
 }

In blogs, normally the content has relatively shorter width to accommodate other things (i.e., widgets) in a single page.

.content {
 max-width: 50%;
 float: left;
 }

Now, we only want the sidebars to show on the right side of our browser only on PCs with high resolution.

@media (min-width: 720px) {
 .sidebar {
 float:right;
 }
 }

Following is the complete code of its implementation:

<!DOCTYPE HTML>
<html>
<style>
.content {
	max-width: 50%;
	float: left;
}

.sidebar {
	font-size: 20px;
	max-width: 50%;
	margin-right: 50px;
}

.sidebar h3 {
	font-size: 30px;
}

@media (min-width: 720px) {
	.sidebar {
        float:right;
    }
}

@media screen and (max-width: 300px) {
 body {
        background-color: red;
      }
 }
</style>
<head>
<title> CSS Media Queries Example</title>
</head>

<body>
<div class="content">
<h1>Blog Content</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin massa purus, dignissim nec nibh elementum, vehicula suscipit tellus. Aenean eget felis condimentum, elementum enim ut, dapibus nisl. Duis porta auctor ligula in pulvinar. Vivamus scelerisque viverra orci, non egestas tortor tristique sit amet. Aenean sollicitudin dui ut dui rutrum aliquet. Nulla ac est sed tellus auctor convallis et ut eros. Sed elementum eleifend interdum. Donec erat lacus, condimentum ut massa et, ornare pulvinar enim. Vestibulum varius luctus vulputate. Sed et massa et mi congue eleifend accumsan eu lectus. Integer eget sagittis tortor. Duis a maximus velit. Nullam euismod finibus arcu et cursus. Nam a malesuada arcu.
</p>
<p>
Maecenas eget diam sed enim porttitor sollicitudin. Praesent aliquet ut nulla sollicitudin ultricies. Aenean eleifend magna ipsum, eu mattis risus finibus eget. Vestibulum ultricies, ipsum id interdum egestas, risus mauris ultricies arcu, at suscipit augue odio a augue. Donec sed erat sit amet risus commodo commodo. Praesent non hendrerit diam, et mollis purus. Aenean vitae viverra diam. Praesent fermentum bibendum nisl, vel ornare nunc fermentum id.
</p>
<p>
Fusce at lacinia dui, sed pharetra nulla. Aliquam vitae laoreet ligula. Fusce blandit mauris lorem, ut eleifend nulla imperdiet ut. Donec pulvinar dapibus nisl sed lobortis. Cras odio dolor, feugiat ut volutpat id, facilisis vel leo. Donec metus nisl, interdum a urna vitae, iaculis blandit elit. Sed elit sapien, tempus vitae elementum eu, sodales id felis.
</p>
<p>
Integer blandit libero vel pellentesque dignissim. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam at dignissim nisl. Aenean et mi nec nibh lacinia faucibus. Pellentesque vitae urna nunc. Proin facilisis felis semper ex sollicitudin ullamcorper. Cras venenatis pulvinar erat, id vulputate felis laoreet sed. Phasellus a porttitor metus. Morbi bibendum purus eros, a efficitur nibh tristique quis. Morbi malesuada tincidunt tempor. Phasellus lorem leo, aliquam ut vulputate posuere, hendrerit vitae risus. Maecenas ut sagittis diam, vitae tincidunt urna. Sed aliquam posuere porta. Phasellus elit mi, viverra non fringilla quis, aliquam eget tellus.
</p>
<p>
In lobortis elementum ornare. Curabitur malesuada, metus pharetra porta blandit, diam sem maximus urna, vel placerat tortor odio ac leo. Sed suscipit tincidunt vulputate. Nulla facilisi. Nulla luctus risus quis interdum efficitur. Quisque ullamcorper ultrices nulla, id ullamcorper diam pretium vitae. Maecenas ac rhoncus nibh. Sed eget fermentum velit, ac pharetra sapien. Nullam in quam faucibus, dignissim magna et, vehicula lorem. Nulla dapibus, justo nec dignissim suscipit, tortor nibh dictum neque, vel fermentum ante neque auctor nulla. Morbi sapien diam, sodales vel elit in, facilisis dictum elit. Nullam porta feugiat pellentesque. 
</p>
</div>
<div class="sidebar">
	<h3>About Me</h3>
	<p>Hello. I am the author of this website.</p>
    <a href="http://example.com/about">Read more...</a>
	<h3>CATEGORIES</h3>
<ul>
	<li>
		<a href="http://example.com/tagged/programming">Programming</a>
	</li>
	<li>
		<a href="http://example.com/tagged/music">Music</a>
	</li>
	<li>
		<a href="http://example.com/tagged/personal">Personal</a>
	</li>
</ul>
	<h3>SUBMIT</h3>
	<p><a href="http://example.com/submit">Submit</a> your article/blog!</p>
</div>
</body>
</html>

 

If you copy the above code in your text editor, save it as “index.html” and open in the browser, then you will see the sidebars on the right side of the page. Try increasing the resolution of your browser till the sidebars moved below the content.

Media Types

TypeDescription
allSuitable for all device
printMatches printers, and devices intended to reproduce a printed display, such as a web browser showing a document in “Print Preview”.
screenMatches all devices that aren’t matched by print or speech.
speechMatches screenreaders and similar devices that “read out” a page.

Other Deprecated Media Type

  • tty
  • tv
  • projection
  • handheld
  • braille
  • embossed
  • aural

Note*: It is not recommend to use given deprecated media types. But user agents are supposed to recognize these media types too but will not match them nothing.

Media Feature

widthmin-widthmax-width
heightmin-heightmax-height
device-widthmin-device-widthmax-device-width
device-heightmin-device-heightmax-device-height
aspect-ratiomin-aspect-ratiomax-aspect-ratio
device-aspect-ratiomin-device-aspect-ratiomax-device-aspect-ratio
colormin-colormax-color
color-indexmin-color-indexmin-color-index
monochromemin-monochromemax-monochrome
resolutionmin-resolutionmax-resolution
scanGrid

Conclusion

In this tutorial, we have learnt about CSS Media Queries and its usage. CSS Media Queries is arguably one of the most useful feature which makes the life of web developer easier and fun. Tumblr blogging platform uses CSS Media Queires in pretty much every of its themes, so you can learn by looking at their HTML code.

Now that you know about this feature, note that you don’t need to manually use this functionality if you are creating a big or giant website, as there are many front-end web development frameworks which automatically supports different devices, such as, Twitter Bootstrap, Jekyll, etc. Thus making your life further easier.

If you have any questions, feel free to ask in the comments section below!

(Note: This is the first tutorial in our series of advanced HTML5/CSS3 tutorials. In the future, we will write more, so stay tuned!)

1 Comment Supporting different screen sizes through CSS4 Media Queries

Leave A Comment

Your email address will not be published. Required fields are marked *