How To Use CSS Media Queries For Responsive Design?
Tags: webdesign, webdev, responsive
Published: 2021-06-23 07:55:24

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](https://www.lambdatest.com/blog/responsive-web-design-all-you-need-to-know/?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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](https://www.w3.org/TR/WD-CSS2/about.html) 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](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/CSS-Media-Queries-1024x576.png)

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](https://www.lambdatest.com/blog/what-is-css-subgrid/?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish). 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](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/CSS-grids-and-subgrids-1024x661.png)

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](https://www.lambdatest.com/blog/complete-guide-on-testng-annotations-for-selenium-webdriver/?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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:

![Media Rules](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/unnamed-4.png)

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:

![LT Browser](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/media_rules_lt_browser.png)

The above code is rendered on a developer friendly browser called [LT browser](https://www.lambdatest.com/lt-browser?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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.

{% youtube RH95O9mOGoc %}

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

![](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/media_query.gif)

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

[![windows.png](https://ucarecdn.com/54002e5e-69ef-4920-b754-fa136cdf95f0/)](https://downloads.lambdatest.com/lt-browser/LTBrowser.exe)

[![linux.png](https://ucarecdn.com/5e50513f-4ae2-4487-8722-d71a948685fd/)](https://downloads.lambdatest.com/lt-browser/LTBrowser.AppImage)

[![macos.png](https://ucarecdn.com/fa0b296b-d708-409f-b6ed-ef99c080b612/)](https://downloads.lambdatest.com/lt-browser/LTBrowser.dmg)

### 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.

![](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/unnamed-5.png)

The above screenshot is taken from [LT browser](https://www.lambdatest.com/lt-browser?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/and_connector_in_media_rules-1-1024x472.png)

 
```
 @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](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/media_rule_or_connector-1024x493.png)

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.

![](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/media_rule_large_screen-1024x611.png)

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](https://www.w3.org/TR/selectors-4/) 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](http://www.lambdatest.com?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) opened in this demo).

**Right-click** and **select Inspect**.

Click the icon shown below after opening the inspect panel.

![responsive_icon_chrome](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/responsive_icon_chrome.png)

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

![responsive_panel](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/responsive_panel.gif)

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](https://www.lambdatest.com/blog/mobile-first-web-design/#:~:text=The%20mobile%2Dfirst%20design%20concept,focus%20more%20on%20mobile%20users?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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](https://www.lambdatest.com/lt-browser?utm_source=dev&utm_medium=Blog&utm_campaign=Harish-23062021&utm_term=Harish) 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.

![](https://www.lambdatest.com/blog/wp-content/uploads/2021/04/pasted-image-0-7-1024x342.png)

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!