DEV Community

Cover image for How to make your webpage responsive using Media Queries.
Amaan Shaikh
Amaan Shaikh

Posted on

How to make your webpage responsive using Media Queries.

One of the most important feature of any website is its ability to be responsive. So let us first understand what is a responsive website.

A responsive website is one that provides the same content on all devices irrespective of their sizes. It does not break if we access on any other devices other than our PC like mobiles, tablets, etc.

Importance of responsiveness

Nowadays due to technological advancements, we are getting devices in a wide variety of shapes and sizes. Just take our laptops for example gone are the days where we used to have a monitor of standard sizes now we get laptops in various ranges of sizes. It is very important for a website to be compatible with all these devices and many more that will come in the future.

In this article, I will help you in making a website responsive using Media Queries.

What are Media Queries?

Media query is a CSS technique introduced in CSS3.

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

So if you want your website font-size to automatically get reduced when the width of the screen is less than equal to 600px you can write the below code in your CSS file:

@media only screen and (max-width: 600px) {
  body {
   font-size; 10px;
  }
} 
Enter fullscreen mode Exit fullscreen mode

Let's understand the above code.

@media - This enables our code to be a media query.
only screen - This ensures our code should be applicable to only screen sizes.
max-width: 600px - This is the breakpoint or condition you can say which applies the styles only when the screen size is less than equal to 600px.

Please note if you have a style in media query already declared, the style inside media query will just get override if the condition is met.

Apart from max-width, we can also use min-width to make sure media query styles are only applied when the screen size is greater than equal to the breakpoint.

There is one more way in which a web page size changes apart from the device size is orientation in mobile devices.

For mobile devices, we have two types of orientation: Portrait and Landscape, and the size of the page changes whenever the orientation changes.

Do not worry! Here come media queries to the rescue.

So if you want to change to webpage color based on the orientation you can use the below code.

@media only screen and (orientation: landscape) {
  body {
    background-color: lightblue;
  }
}
Enter fullscreen mode Exit fullscreen mode

orientation- values can be landscape and portrait

Reference: https://www.w3schools.com/css/css_rwd_mediaqueries.asp

Have a nice day!

Discussion (0)