Media Queries

In this post, I will example at a high level what Media Queries are and why they are so powerful. As we have read in Part 1 of Intro to Web Dev, CSS helps us style a webpage to make it look and feel unique. We can apply any colors, text sizes, and just about any layout changes we need.

CSS is extremely powerful in that it allows you to target any element on the page and manipulate it. Being a query language, you can write expressive statements to get as granular or broad as you want in the element you are trying to target. You can target all images on the page or only images inside a section in the page’s header.

/* Target all images on the page */
img {
  width: 250px;
}

/* Target all images on the page under an element with a header class */
.header img {
  width: 250px;
}

With CSS, you can target elements by what elements are next to, called their siblings. You can also target elements based on what element they sit inside, their parents. The list goes on, but the primary way of targeting an element to style it is via their relationships with other elements on the page. But what if you wanted to style things differently based on the user’s device, mobile phone vs. a laptop? Well, this is where Media Queries come in.

Before I move on, I would like to stress that CSS is an extremely powerful query language, and although I brushed over a few ways to query elements on the page, this is a huge topic. You can find more ways to query here.

Now moving on to Media Queries. Like Regular CSS, Media Queries allow you to target elements on the page. You can target them based on a few other factors this time. Take the image from our previous example. This time with Media Queries, you can style that image differently if it was on a mobile phone vs a desktop like this.

@media screen and (max-width: 480px) {
  .header img {
    width: 150px;
  }
}

@media screen and (max-width: 320px) {
  .header img {
    width: 100px;
  }
}

The above code tells the browser to make the size of an image in the header 150 pixels wide but only if the screen size is 480 pixels wide. It also tells it that on devices where the width of the screen is 320 pixels wide to make the image 100 pixels wide. This way the image does not take too much space on the user’s device because it will get shrunk depending on the device it’s being viewed on.

The full specs can be found here if you are interested in all the way you can target based on different devices, but the most common is the user’s screen size. You can write your styling code to target elements on the page given different ranges of screen sizes so that your pages can work better across all devices.

One Reply to “Media Queries”

Leave a Reply

Your email address will not be published. Required fields are marked *