How To Use CSS Media Queries For Responsive Design?

How To Use CSS Media Queries For Responsive Design?

CSS is one of the fundamental pillars in web development and design. While CSS started as something that can change the style of a web page, every CSS specification iteration now brings more to the table, precisely when it comes to cross browser compatibility.

Today, CSS is more than just “background-colour” and tag specifications that made initial web development days a lot of fun. CSS has become a helping tool in bringing out mobile-first design and responsive web design in web applications without making too much effort.

In this post, we will deep dive into the concept of CSS media queries: a property of CSS that can make some amends to the web page by looking at the device. We shall also see how everything evolved and further focus on how we can implement the responsive design css media queries to develop a seamless user experience for your website.

What are CSS Media Queries?

The CSS media queries started with the CSS2 specification that incorporated the CSS media rule in its library. Media rules were introduced into the CSS after observing the different media devices that were flooding the market and were well received by the consumers.

For example, it was an exciting time when speech devices were introduced that could read the webpage for you. But unfortunately, even though media rules were so important, they failed to impress the developer community. A strong reason being that media devices were not ready for such transformation (at least till that point!).

CSS Media Queries

So, moving ahead, CSS developers thought about a modification in this property. Even though media rules were not working out in the community, they can introduce queries that can analyze one media device and apply CSS accordingly. These were called CSS media queries.

CSS media queries as we know transformed the way we develop a responsive web app today. CSS media queries are conditions and queries that work perfectly in this age of hundreds of devices and browsers.

While media rules looked at a smartphone, CSS media queries looked at the viewport, resolution and even orientation. These media queries gave a unique capability of rendering the content according to the device-type or its orientation bringing us to the next step in responsive web design. The change that CSS developers thought about, was well received and became an integral part of web design, with the help of CSS media queries.

It’s 2021! Do we really need media queries?

The first thing that might come to your mind is “Do we really need CSS media queries, considering the plethora of technologies and specifications coming up with each passing day”? It’s a genuine and common question for someone starting their journey with media queries.

Well CSS is now a lot more mature than it was previously when CSS 2 was introduced. We have so many advanced techniques in CSS now that a lot of the standard issues are covered by new concepts in CSS.

One such thing that comes to mind is CSS grids and subgrids. CSS grids are responsive in nature and are often intended for large layouts. They require manual coding with media queries to shrink and expand the column size according to the device screen.

CSS grids and subgrids

Another part of CSS grids is the CSS flexbox which is also responsive in nature and most appropriate for small scale layouts. As a web developer, you might also have your own set of tools that are highly responsive. These tools bring down our efforts and save a lot of time leaving us with this lingering question “Should we learn media queries right now in 2021”?

I believe there are two things to consider while answering this question, whether we need CSS media queries in 2021. Well, it is definitely true that new CSS techniques and elements give quicker and better results in terms of responsiveness. However, it is also true that as a web developer, I myself would recommend the fellow developers to use the new specs rather than focussing on media queries.

But, the new specifications do not completely replace the control we get through media queries and are merely a solution to only standard issues in web development. For example, in the case of responsive design, CSS media queries will provide more control and options to implement different use cases.

The CSS specifications on the other hand are fixed. CSS grids will always work with the “grid” structure but media queries can be used with a lot of other options. If your project requirements can be completed with the new specifications, it is good enough to use! However, to develop something new and creative, media queries will come to your rescue.

Another perfect reason to learn CSS media queries today is to enhance the CSS specification and elements. While using a CSS responsive element such as CSS grids, you can use the media queries on top of it to enhance its functionalities and add some of your own: such as changing the color (a very basic example).

Therefore, even though it might seem as if CSS media queries are not being used when you start developing a project, you will find a lot of the scenarios that require CSS media queries for their implementation. It is always best to learn and practise them to implement in a web development project.

How do you write media queries in CSS for Responsive design?

The syntax for CSS media queries resembles TestNG annotations which as a novice web developer, you will find a bit unique.

The media query can be implemented by the word “media” as follows:

@media <media_type> connector ( <query> )

As an example:

@media only screen and (max-width: 480px) {
  /* CSS rules to apply /*
}

This media query will look for screens (“only screen” as written) with a max-width of 480px. If it finds one, the conditions will be executed and the changes will be made to the HTML code.

For applying just the media type and not the media expressions (queries), the following values are accepted:

  • all
  • print
  • screen
  • speech
@media print {
   .heading {
     font-size: 12px
   }
}

The above query will make the content with the class name heading to a font-size of 12 pixels when the page needs to be printed.

Media Feature Rules

To achieve responsiveness through our web application, we must know the device size to render specific content. Media feature rules help us achieve that. With media features, we can identify our specific condition and implement CSS accordingly. Although there are a lot of media feature rules, we will discuss just a few important of them for responsive design.

Width and Height Media Feature Rules

The first media feature rule to consider is to check the width and height of the viewport. Width operations can be checked with the “width” property, “max-width” and “min-width” property for bottleneck values.

Example of max-width media feature rule:

@media screen and (max-width: 840px){
  p {
     color: red;
}
}

The complete code for achieving responsive design through media rule can be written as:

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>Media Queries</title>
    <style>
        @media screen and (max-width: 840px){
          p {
            color: red;
          }
        }

    </style>
  </head>
  <body>
    <center>
         <p>Checking Media Rules</p>
    </center>
  </body>
</html>

For a screen having a width of more than 840px, the “p” tag will show the content in black colour as follows:

The above screenshot is taken on the LambdaTest platform.

On a screen of width lower than 840px, the media rule will change the content to the color red and font-size as follows:

The above code is rendered on a developer friendly browser called LT browser which helps in responsive testing and development on 50+ screen resolutions. You can perform mobile website tests on LT Browser faster and easier using features like side-by-side view, scroll sync, instant debugging, network simulation and more. Furthermore, LT Browser allows you to collaborate with your team to scale your development process by integrating with project management tools.

For a much clearer view, you can run the HTML code in your browser and start decreasing the viewport to see the effect.

The above-used browser is Opera on Windows 10 platform. Similarly, you can make use of the height and width rule.

windows.png

linux.png

macos.png

Orientation in CSS Media Query

The orientation of a device is one of the major problems that break the responsiveness of your website. Responsiveness can never be achieved if the web application cannot understand the orientation and respond accordingly. As in media queries, knowing the orientation of the device can help us organise the content differently resulting in more responsiveness.

Orientation media rule can be applied as following example:

 @media (orientation: landscape){
          p {
            color: red;
            font-size: 36px;
          }
        }

The above code will apply the media rules in the landscape orientation while the portrait orientation will work normally.

The above screenshot is taken from LT browser which has the ability to render two devices at the same time for testing.

Connectors in Media Rules

A lot of the time, just one media rule is not enough for achieving responsiveness. What if we want to implement the media rule on specific devices and with specific conditions? For such requirements, we make use of connectors (logical) in media rules. The connectors take three values in CSS media queries:

  • and
  • or
  • not

These connectors have the same meaning as they do in the boolean expressions and in programming languages. To apply an “and” connector, the following code will help you:

@media (orientation: landscape) and (min-width: 1080px){
          p {
            color: red;
            font-size: 36px;
          }
        }

The above code only works when the minimum width of the screen is 1080px and the orientation is landscape. Since a mobile will not fall into this category, let’s see if the media rule works well in the landscape.

nd_connector_in_media_rules

 @media (orientation: landscape), (min-width: 1080px){
          p {
            color: red;
            font-size: 36px;
          }
        }

The above media rule will be applied if either the orientation is landscape or the min-width is 1080px. The following changes can be observed in the mobile devices:

media_rule_or_connector

Since the landscape rule is satisfied, the media rules are applied accordingly. The same effect will be seen on a screen with a width greater than 1080px.

The “not” rule can be applied with the “not” keyword and would be good practice for the readers. Comment below with your unique media queries to help the community.

The above-demonstrated code was introduced in level 3 of the specification. With level 4, we get a little more flexibility in terms of defining the numbers and the intervals without using the logical operators i.e. the connectors. Level 4 specification in media rules introduces ranges into the queries. So, a query as follows:

 @media (orientation: landscape), (min-width: 1080px){
          p {
            color: red;
            font-size: 36px;
          }
        }

Can be written with level 4 specification as follows:

(640px <= width <= 1080px)

Which is a bit better and clearer in defining the media rules. However, there are no restrictions on the developer and both of them can be used to achieve responsiveness.

Breakpoints and Its Methods

The post until now shows us how to achieve responsive web design using the media queries, rules and expressions. It is fun to have control over elements and see them transform as per our wish. But the problem here is, how to decide at which point we want those media rules to be applied to the elements? 640px or 1080px or something else? This number that works as a reflection point is called a breakpoint at which point the media queries get executed. Selecting random breakpoints is a poor responsive design strategy and should never be applied without analysis.

The best way to analyse breakpoints is through the browser’s responsive panel. The responsive panel in the browser allows resizing of the window (or selecting multiple resolutions) helping us in selecting the bottlenecks quickly and precisely.

To open the panel in Google Chrome, open a website (as LambdaTest opened in this demo).

Right-click and select Inspect.

Click the icon shown below after opening the inspect panel.

responsive_icon_chrome

The responsive panel will open up. Here, you can adjust the screen dimensions and check the bottlenecks.

responsive_panel

Notice how the resolution changes as the screen is shrunk/expanded (the top panel). This panel will help the developers to see the breakpoints where the code is breaking out of the screen. The same can then be applied to the media rules.

Mobile browsers have become the primary choice for users all over the world. As far as the design strategy is concerned, it is always recommended to go for a mobile-first design strategy in today’s time for perfect responsive design.

As a developer, keeping mobile secondary on the list might lead to irking your users. Start your development with the mobile devices and gradually move up the chain (or backwards in time). Such a method always ensures that your mobile users are happy and the website you built is responsive. To verify your designs, it is preferred to use a mobile-specific browser such as LT browser as it provides more features, flexibility and scalability.

Cross Browser Compatibility for CSS Media Queries

As you can see in the image below cross browser compatibility for CSS Media queries is really great. However it does not support older versions of internet explorer and mozilla firefox.

Again, browsers keep evolving and there might be chances that these can change over a period of time. Well, as of now you do not need to worry about cross browser compatibility for CSS media queries.

Wrapping It Up!

CSS media queries are a helpful friend in building up a responsive design and developing with more control and enhancement capabilities. Media queries, although started rough, are used exhaustively today in projects and web applications. This post highlighted the main goals of media queries and how to achieve responsiveness with them using different rules and expressions. It amazes me to see such beautiful designs on Codepen and other websites that developers build with minimum library support. Coming to the end of the post, we call for such designs in the comment sections and would love to include the best of them in this post. Hope to see some creative work!