Hello Sunil
Media Queries in CSS

Media Queries in CSS – A Complete Guide

When creating a website for users to view, you want to make sure that the page looks great and intuitive regardless of the users’ devices. These days users access the web from a variety of devices from desktop computers, tablets, mobile phones to assistive technologies.

Designing a website to accommodate these devices can be a daunting task due to different screen sizes, browser viewport, resolution and device type.

There is a particular CSS feature that can make this task approachable and if done right most of the devices accessing your site will get the appropriate user experience. Yes!! we are talking about CSS Media Queries.

Literally speaking the word “media” means the device(s) and “queries” in this context refer to the code that will be used to target these devices.

đź“– Quick summary

CSS media query is used to apply a different set of CSS rules when certain conditions are met.

For example,

@media screen and (max-width: 768px) {
p { font-size:1.2rem }
}

The @media screen and (max-width: 768px) part specifies the conditions to be met. When the conditions are met, p { font-size:1.2rem } will be applied.

Making a website with an adaptable layout is called Responsive Web Design. And CSS media queries are one of the most important parts of responsive design.

In this article, we are going to take a closer look at media queries and how to use them in CSS.

What are media queries?

With a media query, you can write different CSS code for different screen sizes or for different devices, which is very useful when making web pages with responsive design.

You can also have different layout when a user resizes a browser window up or down to a certain width, or height.

In layman words, you can define the media queries are a fundamental part of responsive web designs which are used to customize the visual of the website for the multiple devices.

Since media query is a logical expression it can be resolve to either true or false. The result of the query will be true if the media type specified in the media query matches the type of device the document is being displayed on, as well as all expressions in the media query are satisfied.

When a media query is true, the related style sheet or style rules are applied to the target device. Here’s a simple example of the media query for standard devices.

/* When the browser is at least 600px and above */
@media screen and (min-width: 600px) {
  .element {
    /* Apply some styles */
  }
}

Media queries is the closest you will come to real programming while coding in CSS. Most of CSS is just about telling the browser how to display certain elements.

Media queries, on the other hand, actually tell the browser to check on something (in this case, the size of the browser window or the type of device being used), and then display different things depending on the results of that check. It’s almost like an “if, then” statement, for CSS.

Ok, lets know about the syntax of media queries now.

Syntax anatomy of a media query

So now that you know media queries help with styling different screen sizes, you might be wondering how they work, right?

Responsive web design is vital for any successful web project and CSS media queries are vital for a successful responsive website.

At its most basic level, media queries act as a switch for triggering styles based on a set of rules. So, how does that switch work? Let’s understand more deeply through its syntax,

Media Queries in CSS - Syntax anatomy of a media query - img 1

CSS media queries consist of an (optional) media type and one or more expressions called media features.

We can also target different media types under a variety of conditions through logical operators. If the condition and/or media types meet, then the rules inside the media query will be applied, otherwise, they won’t.

The syntax may seem complicated at the beginning, so let’s explain each part one by one in details.

@media

@media [media-type] ([media-feature]) {
  /* css styles */
}

A media query starts with the @media rule and assign a CSS block to a page only if the following conditions are met.

A typical media query will query the width and height of the browser window as well as the type of device.

Media queries are used to query media type (smartphone, tablet, printer, TV) and media characteristics such as screen orientation, resolution, height, width, or colors, and, as a result, to set breakpoints.

Media types

@media screen {
/* CSS code for screen output */
}

What type of media are we trying to target? In many (if not most) cases, you will see a screen value used here, which makes sense since many of the media types we are trying to match are devices with screens attached to them.

Media queries are case-insensitive and if query contain UNKOWN media type it will be false by default.

But screens aren’t the only type of media we can target, of course. There are many kinds of devices but we can group them into 4 categories:

TypeDescription
screenApply to all the screens – Monitors, TV, smartphone,
and tablet screens
printFor the printed media only – i.e.
When the user prints your web page
speechFor screen readers that “read” the page out loud
allFor all media types

* screen is the default.

If we don’t apply a media type, the @media rule selects all types of devices by default.

For example, when we want to select only screens, we are going to set the screen keyword right after the @media rule.

@media screen and (max-width: 480px) {
  .text {
    font-size: 16px;
  }
}

Or you can follow the below pattern:

@media only screen (min-width: 1281px) {

//CSS properties  

}

Here we use @media rule of CSS and inside curly braces we can use our regular CSS properties.

Media features

Once we define the type of media we are trying to match, we can start defining what features we are trying to match it to.

Media features are expressions that set one or more requirements for an output device, which must be met in order to include the CSS resources.

For example if we apply min-width:320px, it means that the specified CSS properties will only be applied if the devices have a minimum width of 320px. If the device width is less than 320px the CSS properties will not work.

@media screen and (min-width: 320px) {

  /* CSS */

}

That mean, min-width, max-width, orientation, height, width, and resolution of a display are media features with specific values. An expression is true if the feature is met, and false if it is not.

By media feature we tell the browser which condition must meet the output device specified for the condition to be true and apply the code contained in the media query.

If multiple media features are defined in one query, all must be true for the entire query to be true.

An example code for querying all media types including the media feature of landscape:

@media all and (orientation: landscape) {
/* CSS code for output in landscape mode */
}

Operators

Media queries support logical operators like many programming languages so that we can match media types based on certain conditions.

The @media rule is itself a logical operator that is basically stating that “if” the following media types and features are matches, then do some stuff.

đź’ˇ Note

We can compose complex media queries using logical operators, including not, and, and only. 

You can also combine multiple media queries in a comma-separated list; if any of the media queries in the list is true, the entire media statement returns true. (This is equivalent to an or operator.)

We have the following operators provided by media queries.

and

The and operator is the one you will probably use the most. It is used for combining multiple media features together into a single media query.

It requires that all conditions specified must be met before the styling rules will take effect.

Example:

/* Matches screen between 320px AND 768px */
@media screen (min-width: 320px) and (max-width: 768px) {
  .element {
    /* Styles! */
  }
}

In the above example, the CSS rules inside the .element class of the media query will only be applied if the browser window width is between 320px and 768px.

Media queries include curly braces {}. CSS style rules also include curly braces {}, so you will see CSS curly braces nested inside media query curly braces.

, (comma)

Comma (,) operator basically works like or operator. When a single query becomes true, the style will be applied.

Example:

/* 
  Matches screens where either the user prefers dark mode or 
  the screen is at least 1200px wide */
@media screen (prefers-color-scheme: dark), (min-width 1200px) {
  .element {
    /* Styles! */
  }
}

Above media query will apply when the device is at least 1200px in size or the user prefers a color scheme of dark. Because we have used the comma (,operator here.

not

The not operator is used to negate a media query, returning true if the query would otherwise return false.

not operator basically reverses the condition of the media query. In other words, perhaps we want to target devices by what they do not support or match.

not can only be used to negate an entire media query, so it must be placed at the beginning of it (or after a comma).

Example:

@media print and ( not(color) ) {
  body {
    background-color: none;
  }
}

This declaration removes the body’s background color when the device is a printer and can only show one color.

only

It is basically used for old browsers that do not support media type with media feature. The only operator is used to apply a style only if an entire query matches.

This means the only keyword is useful for preventing older browsers from applying selected styles. If you have to deal with an old web browser this keyword will definitely come in handy but this would be rare these days.

đź’ˇ Note

not operator has no effect on a modern browser.

Like old browser can interpret screen and (min-width: 768px) as the screen only and apply to all screens, to avoid this we have to use the only operator.

With the not and only operators we can play to group or exclude a particular type of media type.

@media only screen (min-width: 768px) {

//CSS properties  

}

đź’ˇ Media query operators

You can create advanced CSS media queries by using logical operators and, only and not. Developers combine several media queries by separating them by commas.

• and: combines several media features. Both need to be true.
• only: applies styling properties only if the entire query matches.
• not: negates a media query by delivering true when the response should have been false.

Breakpoints in media queries

Breakpoints are points which determine when to change the layout and adapt the new rules inside the media queries.

We recommend that you start with the design for the smallest output device (smartphones) when you layout a responsive web page and then adapt it for tablets, laptops, and even large monitors with breakpoints and CSS.

đź’ˇ Note

CSS breakpoints are a huge part of responsive designs. You use breakpoints with media queries to set points where websites adjust to the width of devices. Therefore, you can control the layout of websites and change them according to users’ devices.

Media Queries in CSS - Breakpoints  - img 12

Source: bitdegree

A breakpoint and the corresponding CSS have to be defined whenever the display is no longer consistent. CSS in this media query only overwrites the styles that are changed by the breakpoint.

Example code for a breakpoint at 480px width:

@media (max-width: 480px) {
  .text {
    font-size: 16px;
  }
}

Here, the breakpoint is 480px. Now the media query knows when to set or overwrite the new class. Basically, if the width of a device is smaller than 480px, the text class will be applied, otherwise, it won’t.

To ensure correct display on each device, a viewport meta tag has to be integrated into the <head> area of HTML code. This meta tag tells browsers how to handle the dimensions and scaling of the page. The syntax is:

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

With width=device-width browsers are instructed to use the width of the screen in device-independent pixels. The directive initial-scale=1.0 guarantees a 1:1 relation between CSS pixels and device-independent pixels.

đź’ˇ Note

By setting initial-scale to 1, we control the initial page zoom level (that is, the amount of zoom upon page load).

If you have designed your web page to be responsive, then your fluid, dynamic layout should fill the smartphone screen in an intelligent way without requiring any initial zoom.

In addition, we can disable zoom completely with user-scalable=false.

Common Breakpoints: Is there a standard resolution?

One of the most commonly asked questions is “Which breakpoint should I use?”. There are a ton of devices on the market so we can’t and we shouldn’t define fixed breakpoints for each of them.

That’s why we can’t say that there is a standard resolution for devices, but there are some commonly used breakpoints in daily programming. If you are using a CSS framework (like Bootstrap, Bulma, etc.) you can also use their breakpoints.

Now let’s see some common breakpoints for widths of devices:

Bootstrap common breakpoints:

BreakpointClass infixDimensions
X-SmallNone <576px
Small sm ≥576px
Medium md≥768px
Largelg ≥992px
Extra largexl ≥1200px
Extra extra large xxl ≥1400px

Source : Bootstrap

Common breakpoints (our recommendation):

  • 320px — 480px: Mobile devices
  • 481px — 768px: iPads, Tablets
  • 769px — 1024px: Small screen laptops, iPad pros
  • 1025px — 1280px: Desktops, laptops
  • 1281px and more —  iMac, Big desktop monitor

Or

  • 320px — 480px: Mobile devices
  • 481px — 768px: iPads, Tablets
  • 769px — 1024px: Small screen laptops, iPad pros
  • 1025px — 1200px: Desktops, large screens
  • 1201px and more —  Extra large screens, TV

âť— Important

Always put your media queries at the end of your CSS file.

Breakpoints from community #1

/* 
   iMacs, Big desktop monitor.
*/

@media (min-width: 1281px) {

  /* CSS */

}

/* 
 Laptops,Desktop monitors,ipad pros
*/

@media (min-width: 1025px) 
  and (max-width: 1280px) {

  /* CSS */

}

/* 
  portrait tablets and ipads
*/

@media (min-width: 768px) 
  and (max-width: 1024px) {

  /* CSS */

}

/* 
  Landscape tablets and ipads
*/

@media (min-width: 768px) 
  and (max-width: 1024px) 
  and (orientation: landscape) {

  /* CSS */

}

/* 
Landscape for mobiles and tablets
*/

@media (min-width: 481px) 
  and (max-width: 767px) 
  and (orientation: landscape)  {

  /* CSS */

}

/* 
 Mostly all smartphones
*/

@media (min-width: 320px) 
  and (max-width: 480px) {

  /* CSS */

}

Breakpoints from community #2

// MD devices (tablets, 768px and up)
@media (min-width: 768px) { }

// LG devices (desktops, 1024px and up)
@media (min-width: 1024px) { }

// XL devices (large desktops, 1200px and up)
@media (min-width: 1200px) { }

// XXL devices (large desktops, 1500px and up)
@media (min-width: 1500px) { }

As we said above, these breakpoints can differ and there is no standard exactly defined, but these are some commonly used ones.

How to hide elements in media queries

CSS media queries can hide elements when certain criteria are true.

Mobile web users spend more time finding information on small screens. You can help them have a better experience by hiding the non-essential elements.

You need to set the display property to none when the width of browser windows gets smaller than a certain @media breakpoint, for example, 600px:

/* The element will be hidden if the screen is 600px wide or less */

@media only screen and (max-width: 600px) { 
  div.example {
    display: none;
  }
}

How to change font size in media queries

CSS media queries also adjust the font size based on the screen size. Making information easy-to-read is one of the major goals of any responsive website.

Check the following example to learn to use the font-size property together with @media rule and CSS width.

/* Font size of div elements will be 70px when the screen is 481px or wider */

@media only screen and (min-width: 481px) { 
   div.example {
      font-size: 70px;
   }
}

/* If the screen is 480px or less, the font of div elements will be 25px */

@media only screen and (max-width: 480px) { 
   div.example {
      font-size: 25px;
  }
}

How to work with images in media queries

Scaling images for responsive design is simple enough. However, there are few issues to look out for, such as loss of detail and images being squeezed down to fit the container while taking up most of the page on smaller devices.

To create scalable images, simply add the following code to your stylesheet:

img {
    max-width: 100%;
}

This will scale down the image to fit within a container that is smaller than the image’s width. Setting the max-width to 100% means that the image won’t scale up any bigger than its actual size when called for larger viewports.

min-width & max-width

min-width and max-width are the most confusing part about using media queries but we will do our best to break each feature down so that you can understand them and know when to use what.

min-width

To use the min-width targeting feature, we simply add it in between the parenthesis in our initial media statement like so:

@media (min-width: 1600px) {
/* Your new CSS changes go here */
}

In the example above, the min-width property will target any screen with a width of 1600px or greater.

You can also think of this as the minimum screen size that this media query will target is 1600px or greater, this same way of thinking applies with the other targeting features.

max-width

Max width will do the exact opposite of min-width by targeting all screen sizes that are less than or equal to the number of pixels you chose. The syntax follows the same structure.

@media (max-width: 600px) {
/* Your new CSS changes go here */
}

The code above will execute on all screens with a width of 600px or less. You should also note that you can also use min-height and max-height properties which will do the exact same thing as the width properties but with height instead.

How to target specific screen sizes

One final thing we would like to touch upon that how to target a single specific screen size. We can achieve this with a slightly different syntax which is as follows:

@media (min-width: 767px)and (max-width: 768px) {
/* This will target your specific screen size*/
}

We can also use this method to target screen sizes that fall within a certain range of pixels. Simply set the min and max values to your desired sizes to have a media query affect a certain range of devices.

Media queries example

Resources & Further study

Conclusion

Responsive design is a must in today’s web design and development field. Media queries are one of the most important parts of building responsive layouts, and we hope you find our post helpful for understanding how media queries work.

In summary, basic CSS3 media queries are actually simple to learn and easy to add to cascading stylesheets to target different screen sizes. They just take a little practice.

As always, feel free to comment, critique, and make suggestions.

Thank you for reading!

How useful was this post?

Click on a star to rate it!

Average rating 0 / 5. Vote count: 0

No votes so far! Be the first to rate this post.

We are sorry that this post was not useful for you!

Let us improve this post!

Tell us how we can improve this post?

Similar articles you may like

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.

Add comment

Stay Updated

Want to be notified when our article is published? Enter your email address below to be the first to know.

Sunil Pradhan

Hi there đź‘‹ I am a front-end developer passionate about cutting-edge, semantic, pixel-perfect design. Writing helps me to understand things better.