Media Queries in CSS

hira_zaira

zaira

Posted on July 2, 2023

Media Queries in CSS

A responsive website is a website that adapts according to its target device. For example a responsive website would adapt its layout to suit a laptop, a phone and a tablet. A phone has a smaller display, so a responsive website might make the font-size a bit bigger in smaller screens.

But how do you do that? You can use media queries in your CSS to explicitly tell your website to change according to the screen size.

Table of contents

Targeting smaller screens with media queries

Let's discuss an example of defining media queries.

@media (max-width:600px) {

/*
CSS for screens equal to or below 600px
*/

}
Enter fullscreen mode Exit fullscreen mode

In the code above, 600px is the breaking point. This means that you are targeting screen sizes equal to or below 600px.

In the code below, any screen equal to or below 600px would have its background set to red.

@media (max-width:600px) {

  body{
    background-color: red;
  }

}
Enter fullscreen mode Exit fullscreen mode

Targeting larger screens with media queries

In the below, example 900px is the breaking point. It is targeting screens whose width is at least 900px.

@media (min-width:900px) {

/*
CSS for screens equal to or above 900px
*/

}
Enter fullscreen mode Exit fullscreen mode

In the below example, any screen greater than 900px would have its background set to green.

@media (min-width:900px) {

  body{
    background-color: green;
  }

}

Enter fullscreen mode Exit fullscreen mode

Targeting a screen range using media queries

The below code targets any screen greater than 600px and smaller than 900px.

@media (min-width:600px) and (max-width:900px){

  body{
    background-color: burlywood;
  }

}
Enter fullscreen mode Exit fullscreen mode

See media queries in action

Go to this link to see media queries in action! Adjust the screen size and see how media queries are being applied!

To review the code, go to this GitHub repo.

Image description

Wrapping up!

I hope you found this tutorial helpful. Thank you for reading till the end.

I would love to connect with you on any of these platforms.

Image description

💖 💪 🙅 🚩
hira_zaira
zaira

Posted on July 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to build a Piano With CSS.
webdev How to build a Piano With CSS.

October 14, 2023

Media Queries in CSS
webdev Media Queries in CSS

July 2, 2023