How to Use Media Queries in CSS for Responsive Design
CSS media queries transform the way to develop responsive web applications. Read this article to know how to achieve responsiveness with CSS media queries
Join the DZone community and get the full member experience.
Join For FreeCSS is one of the fundamental pillars of 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 media queries in CSS: 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.
New to CSS Selectors? Check out this Ultimate CSS Selector cheat sheet to boost your web designing career.
What Are Media Queries in CSS?
The media queries in CSS 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 users.
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 is that media devices were not ready for such transformation (at least until that point!).
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.
As we know, media queries in CSS transformed how 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 orientation. These media queries in CSS 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 CSS developers thought about was well received and became an integral part of web design with the help of CSS media queries.
Do We Really Need CSS 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 in CSS.
CSS is now much more mature than it was 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 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.
Another part of CSS grids is the CSS Flexbox, which is also responsive and most appropriate for small-scale layouts. You might also have your own set of highly responsive tools as a web developer. These tools bring down our efforts and save a lot of time, leaving us with this lingering question “Should we learn CSS media queries”?
I believe there are two things to consider while answering this question, whether we need CSS media queries in 2022. Well, it is definitely true that new CSS tricks and elements give quicker and better results in terms of responsiveness. However, it is also true that as a web developer, I would recommend my fellow developers to use the new specs rather than focus 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, media queries in CSS 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 many other options. It is good enough to use if your project requirements can be completed with the new specifications! However, media queries will come to your rescue to develop something new and creative.
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 media queries in CSS are not being used when you start developing a project, you will find a lot of scenarios that require CSS media queries for their implementation. It is always best to learn and practice them to implement in a web development project.
How Do You Write Media Queries in CSS for Responsive Design?
The syntax for media queries in CSS resembles TestNG annotations, which you will find a bit unique as a novice web developer.
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
- 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. We can identify our specific condition with media features 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” properties 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 rules 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 color 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:
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.
The code was 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, test websites on different network conditions, and more. Furthermore, LT Browser allows you to collaborate with your team to scale your development process by integrating with project management tools.
Orientation in CSS Media Queries
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 device’s orientation can help us organize the content differently, resulting in more responsiveness.
The orientation media rule can be applied as the 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 can render two devices simultaneously 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 programming languages. To apply “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.
@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 mobile devices:
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 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:
(min-width: 640px) and (max-width:1080px)
Can be written with level 4 specifications 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; both can be used to achieve responsiveness.
Breakpoints and Their Methods
The post, until now, shows us how to achieve responsive web design using media queries in CSS, rules, and expressions. It is fun to control elements and see them transform as per our wishes. But the problem 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 when the media queries get executed.
Selecting random breakpoints is a poor responsive design strategy and should never be applied without analysis. Please refer to our blog on CSS breakpoints for responsive design to know more about breakpoints.
The best way to analyze breakpoints is through the browser’s responsive panel. The responsive panel in the browser allows resizing the window (or selecting multiple resolutions), helping us select the bottlenecks quickly and precisely.
To open the panel in Google Chrome, open a website, then:
- Right-click and select Inspect.
- Click the icon shown below after opening the Inspect panel.
- The responsive panel will open up. Here, you can adjust the screen dimensions and check the bottlenecks.
Notice how the resolution changes as the screen is shrunk/expanded (the top panel). This panel will help the developers 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. Regarding the design strategy, it is always recommended to go for a mobile-first design strategy in today’s time for perfect responsive design. Check our blog on how to perform mobile web browser testing.
As a developer, keeping mobile secondary on the list might irk your users. Start your development with mobile devices and gradually move up the chain (or backward in time). Such a method always ensures that your mobile users are happy and the website you built is responsive. To verify your designs, a mobile-specific browser such as LT Browser is preferred to verify your designs as it provides more features, flexibility, and scalability.
Cross-Browser Compatibility for Media Queries in CSS
As seen in the image below, cross-browser compatibility for media queries in CSS is really compatible with many browsers. 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. As of now, you do not need to worry about cross-browser compatibility for media queries in CSS.
Wrapping it Up!
Media queries in CSS are a helpful friend in building up a responsive design and developing with more control and enhancement capabilities. Media queries in CSS although started rough, are used exhaustively today in projects and web applications. You can follow this CSS cheat sheet to brush up on your CSS skills.
This post highlighted the main goals of media queries in CSS 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 minimal 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!
Published at DZone with permission of Harish Rajora. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments