Mastering CSS Responsive Media Queries For Optimal Responsive Design
Harish Rajora
Posted On: July 5, 2022
100791 Views
6 Min Read
CSS responsiveness 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 responsive specification iteration now brings more to the table, precisely when it comes to cross browser compatibility.
Today, responsive CSS framework is more than just “background-colour” and tag specifications that made initial web development days a lot of fun. Media query 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 responsive 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.
TABLE OF CONTENTS
What are CSS media queries?
The media queries in responsive CSS framework started with the CSS2 specification that incorporated the CSS media queries rule in its library. Media responsive CSS 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 being that media devices were not ready for such transformation (at least till that point!).
So, moving ahead, responsive CSS developers thought about a modification in this property. Even though media responsive CSS rules were not working out in the community, they can introduce the CSS media queries that can analyze one media device and apply responsive CSS framework accordingly. These were called CSS responsive media queries.
As we know, media queries in CSS transformed how we develop a responsive web app today. Responsive CSS media query is the condition and queries that work perfectly in this age of hundreds of devices and browsers.
While media responsive CSS rules looked at a smartphone, media query CSS 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 responsive developers thought about was well received and became an integral part of web design with the help of responsive CSS media queries.
Do we really need CSS media queries?
The first thing that might come to your mind is, “Do we really need media queries in CSS 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 responsive CSS framework.
CSS responsiveness 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 responsive CSS 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 about the media queries in CSS”?
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 responsive 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 responsive CSS 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 responsiveness is 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 responsive CSS media queries 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:
1 |
@media <media_type> connector ( <query> ) |
As an example:
1 2 3 |
@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
1 2 3 4 5 |
@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 responsive CSS media queries 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:
1 2 3 4 5 |
@media screen and (max-width: 840px){ p { color: red; } } |
The complete code for achieving responsive design through media rules can be written as:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<!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.
Check out the below tutorial on getting started with LT Browser:
Subscribe to our LambdaTest YouTube Channel and stay updated with the latest tutorial around Selenium testing, Cypress E2E testing, Playwright testing, and more.
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:
1 2 3 4 5 6 |
@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 a responsive CSS media query:
- 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:
1 2 3 4 5 6 |
@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.
1 2 3 4 5 6 |
@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:
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:
1 |
(min-width: 640px) and (max-width:1080px) |
Can be written with level 4 specification as follows:
1 |
(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.
You can also refer to the below tutorial on how to perform responsive testing on the LambdaTest platform.
Breakpoints and Its Methods
The post, until now, shows us how to achieve responsive web design using media queries in responsive 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 (as LambdaTest opened in this demo).
- Right-click and select Inspect.
- Click the icon shown below after opening the Inspect panel.
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 the 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 CSS media queries
As seen in the image below, cross browser compatibility for media queries in CSS responsiveness is crucial. 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 the responsive CSS framework.
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 responsive 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 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!
Frequently Asked Questions (FAQs)
What is CSS media queries?
CSS media queries are useful for modifying websites and apps based on the device type or a specific characteristic, such as the screen size or viewport width.
Can you use media queries in CSS?
Even though media queries are typically associated with CSS, they can also be used in HTML and JavaScript. Also, you can use media queries in HTML directly.
What is the responsive in CSS?
A responsive web design means your site will look great on any device: desktop, tablet, or phone. A responsive design is achieved by using CSS and HTML to resize, hide, shrink, enlarge, or move the content to make it look good on any screen.
How do I make my CSS code responsive?
The viewport meta tag must be included in the HTML code to make a web page responsive. This sets the page width to the device width and the initial zoom to 1. If the meta tag is not included, mobile or tablet users will see a desktop version of your website that might not fit properly on their screens.
What is responsive coding?
Responsive coding refers to designing and developing websites or applications that can adapt and adjust their layout and content to different screen sizes and devices. A responsive website can be viewed and used effectively on desktops, laptops, tablets, and smartphones without losing functionality or usability.
What is a media query CSS?
Media queries allow you to apply different CSS styles depending on the type of device being used or other characteristics such as screen resolution or browser viewport width. They are used for the following: To conditionally apply styles with @media or @import rules.
How to use a media query in CSS?
Media queries in CSS allow you to apply different styles to a webpage based on the characteristics of the device or screen size. To use a media query in CSS, you can follow these steps:
- Define the media query using the @media rule followed by the media type and the condition to apply the styles.
- Within the curly braces of the media query, write the CSS styles that you want to apply to the targeted screens.
You can also use other media types such as print or speech, and other conditions such as minimum width or height, device orientation, etc., to target specific devices or scenarios.
How to write media queries in CSS?
Write a media query in CSS by using the @media rule and specifying the conditions, such as screen size, orientation, or device type, within parentheses. Inside the curly braces, define the CSS styles to be applied under those conditions.
How to use media query in inline CSS?
Using media queries in inline CSS is not recommended. It is best to separate the CSS code into an external stylesheet or include it within the < style >
tags in the < head >
section of an HTML document. This promotes better organization, maintainability, and reusability of CSS styles.
How to apply media query in CSS?
Apply a media query in CSS by wrapping the desired CSS styles within an @media rule, specifying the desired conditions within parentheses. These conditions can target specific screen sizes, orientations, or device types, allowing for responsive design and layout adjustments.
How to add a media query in CCS?
To add a media query in CSS, use the @media
rule followed by the desired conditions within parentheses, and enclose the CSS styles inside curly braces. Example: @media (max-width: 600px) { /* CSS styles here */ }.
Got Questions? Drop them on LambdaTest Community. Visit now