What is css media queries

Media queries

Медиавыражения (media queries) являются ключевым компонентом отзывчивого дизайна (en-US) , который делает возможным для CSS адаптироваться в зависимости от различных параметров или характеристик устройства. Например, медиавыражение может применить различные стили, если экран меньше определённого размера, или в зависимости от того находится устройство в портретном или альбомном режиме. @media at-правило используется чтобы задать условия применения стилей к документу.

In addition, the Window.matchMedia() method can be used to test the window against a media query. You can also use MediaQueryList.addListener() (en-US) to be notified whenever the state of the queries changes. With this functionality, your site or app can respond to changes in the device configuration, orientation, or state.

You can learn more about programmatically using media queries in Testing media queries.

Reference

At-rules

Guides

Introduces media queries, their syntax, and the operators and media features which are used to construct media query expressions.

Describes how to test media queries from your JavaScript code, programmatically, to determine the state of the device, and to set up listeners that let your code be notified when the results of media queries change (such as when the user rotates the screen, causing an orientation change).

Читайте также:  Выравнивание текста

Specifications

Specification Status Comment
CSS Conditional Rules Module Level 3 Кандидат в рекомендации
Media Queries Level 4 Кандидат в рекомендации
Media Queries Рекомендация
CSS Level 2 (Revision 1) Рекомендация Initial definition

Found a content problem with this page?

This page was last modified on 21 июн. 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Responsive Web Design — Media Queries

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

Example

If the browser window is 600px or smaller, the background color will be lightblue:

Add a Breakpoint

Earlier in this tutorial we made a web page with rows and columns, and it was responsive, but it did not look good on a small screen.

Media queries can help with that. We can add a breakpoint where certain parts of the design will behave differently on each side of the breakpoint.

Desktop

Phone

Use a media query to add a breakpoint at 768px:

Example

When the screen (browser window) gets smaller than 768px, each column should have a width of 100%:

@media only screen and (max-width: 768px) /* For mobile phones: */
[class*=»col-«] width: 100%;
>
>

Always Design for Mobile First

Mobile First means designing for mobile before designing for desktop or any other device (This will make the page display faster on smaller devices).

This means that we must make some changes in our CSS.

Instead of changing styles when the width gets smaller than 768px, we should change the design when the width gets larger than 768px. This will make our design Mobile First:

Example

/* For mobile phones: */
[class*=»col-«] width: 100%;
>

Another Breakpoint

You can add as many breakpoints as you like.

We will also insert a breakpoint between tablets and mobile phones.

Desktop

Tablet

Phone

We do this by adding one more media query (at 600px), and a set of new classes for devices larger than 600px (but smaller than 768px):

Example

Note that the two sets of classes are almost identical, the only difference is the name ( col- and col-s- ):

/* For mobile phones: */
[class*=»col-«] width: 100%;
>

It might seem odd that we have two sets of identical classes, but it gives us the opportunity in HTML, to decide what will happen with the columns at each breakpoint:

HTML Example

For desktop:

The first and the third section will both span 3 columns each. The middle section will span 6 columns.

For tablets:

The first section will span 3 columns, the second will span 9, and the third section will be displayed below the first two sections, and it will span 12 columns:

Typical Device Breakpoints

There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target five groups:

Example

/* Small devices (portrait tablets and large phones, 600px and up) */
@media only screen and (min-width: 600px)

/* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px)

/* Large devices (laptops/desktops, 992px and up) */
@media only screen and (min-width: 992px)

/* Extra large devices (large laptops and desktops, 1200px and up) */
@media only screen and (min-width: 1200px)

Orientation: Portrait / Landscape

Media queries can also be used to change layout of a page depending on the orientation of the browser.

You can have a set of CSS properties that will only apply when the browser window is wider than its height, a so called «Landscape» orientation:

Example

The web page will have a lightblue background if the orientation is in landscape mode:

Hide Elements With Media Queries

Another common use of media queries, is to hide elements on different screen sizes:

Example

/* If the screen size is 600px wide or less, hide the element */
@media only screen and (max-width: 600px) div.example display: none;
>
>

Change Font Size With Media Queries

You can also use media queries to change the font size of an element on different screen sizes:

Variable Font Size.

Example

/* If the screen size is 601px or more, set the font-size of

to 80px */
@media only screen and (min-width: 601px) div.example font-size: 80px;
>
>

/* If the screen size is 600px or less, set the font-size of to 30px */
@media only screen and (max-width: 600px) div.example font-size: 30px;
>
>

CSS @media Reference

For a full overview of all the media types and features/expressions, please look at the @media rule in our CSS reference.

Источник

A Complete Guide to CSS Media Queries

Media queries can modify the appearance (and even behavior) or a website or app based on a matched set of conditions about the user’s device, browser or system settings.

Brought to you by DigitalOcean

DigitalOcean has the cloud computing services you need to support your growth at any stage. Get started with a free $200 credit!

CSS Media queries are a way to target browser by certain characteristics, features, and user preferences, then apply styles or run other code based on those things. Perhaps the most common media queries in the world are those that target particular viewport ranges and apply custom styles, which birthed the whole idea of responsive design.

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

There are lots of other things we can target beside viewport width. That might be screen resolution, device orientation, operating system preference, or even more among a whole bevy of things we can query and use to style content. Looking for a quick list of media queries based on the viewports of standard devices, like phones, tablets and laptops? Check out our collection of snippets.

Media queries are commonly associated with CSS, but they can be used in HTML and JavaScript as well. HTML There are a few ways we can use media queries directly in HTML. There’s the element that goes right in the document . In this example. we’re telling the browser that we want to use different stylesheets at different viewport sizes:

Why would you want to do that? It can be a nice way to fine-tune the performance of your site by splitting styles up in a way that they’re downloaded and served by the devices that need them. But just to be clear, this doesn’t always prevent the stylesheets that don’t match those media queries from downloading, it just assigns them a low loading priority level. So, if a small screen device like a phone visits the site, it will only download the stylesheets in the media queries that match its viewport size. But if a larger desktop screen comes along, it will download the entire bunch because it matches all of those queries (well, minus the print query in this specific example). That’s just the element. As our guide to responsive images explains, we can use media queries on element, which informs the element what version of an image the browser should use from a set of image options.

Again, this can be a nice performance win because we can serve smaller images to smaller devices — which presumably (but not always) will be low powered devices that might be limited to a data plan. And let’s not forget that we can use media queries directly on the

CSS Again, CSS is the most common place to spot a media query in the wild. They go right in the stylesheet in an @media rule that wraps elements with conditions for when and where to apply a set of styles when a browser matches those conditions.

/* Viewports between 320px and 480px wide */ @media only screen and (min-device-width: 320px) and (max-device-width: 480px) < .card < background: #bada55; >>

It’s also possible to scope imported style sheet but as a general rule avoid using @import since it performs poorly.

/* Avoid using @import if possible! */ /* Base styles for all screens */ @import url("style.css") screen; /* Styles for screens in a portrait (narrow) orientation */ @import url('landscape.css') screen and (orientation: portrait); /* Print styles */ @import url("print.css") print;

JavaScript We can use media queries in JavaScript, too! And guess, what? They’re work a lot like they do in CSS. The difference? We start by using the window.matchMedia() method to define the conditions first. So, say we want to log a message to the console when the browser is at least 768px wide. We can create a constant that calls matchMedia() and defines that screen width:

// Create a media condition that targets viewports at least 768px wide const mediaQuery = window.matchMedia( '( min-width: 768px )' )
// Create a media condition that targets viewports at least 768px wide const mediaQuery = window.matchMedia( '( min-width: 768px )' ) // Note the `matches` property if ( mediaQuery.matches )

Unfortunately, this only fires once so if the alert is dismissed, it won’t fire again if we change the screen width and try again without refreshing. That’s why it’s a good idea to use a listener that checks for updates.

// Create a condition that targets viewports at least 768px wide const mediaQuery = window.matchMedia('(min-width: 768px)') function handleTabletChange(e) < // Check if the media query is true if (e.matches) < // Then log the following message to the console console.log('Media Query Matched!') >> // Register event listener mediaQuery.addListener(handleTabletChange) // Initial check handleTabletChange(mediaQuery)

Check out Marko Ilic’s full post on “Working with JavaScript Media Queries” for a deeper dive on this, including a comparison of using media queries with an older JavaScript approach that binds a resize event listener that checks window.innerWidth or window.innerHeight to fire changes.

Syntax for CSS media queries.

Now that we’ve seen several examples of where media queries can be used, let’s pick them apart and see what they’re actually doing.

@media [media-type] ([media-feature]) < /* Styles! */ >

The first ingredient in a media query recipe is the @media rule itself, which is one of many CSS at-rules. Why does @media get all the attention? Because it’s geared to the type of media that a site is viewed with, what features that media type supports, and operators that can be combined to mix and match simple and complex conditions alike. Media types

  • all : Matches all devices
  • print : Matches documents that are viewed in a print preview or any media that breaks the content up into pages intended to print.
  • screen : Matches devices with a screen
  • speech : Matches devices that read the content audibly, such as a screenreader. This replaces the now deprecated aural type since Media Queries Level 4.

To preview print styles in a screen all major browsers can emulate the output of a print stylesheet using DevTools. Other media types such as tty , tv , projection , handheld , braille , embossed and aural have been deprecated and, while the spec continues to advise browsers to recognize them, they must evaluate to nothing. If you are using one of these consider changing it for a modern approach.

Once we define the type of media we’re trying to match, we can start defining what features we are trying to match it to. We’ve looked at a lot of examples that match screens to width, where screen is the type and both min-width and max-width are features with specific values.

But there are many, many (many!) more “features” we can match. Media Queries Level 4 groups 18 media features into 5 categories.

Feature Summary Values Added
width Defines the widths of the viewport. This can be a specific number (e.g. 400px ) or a range (using min-width and max-width ).
height Defines the height of the viewport. This can be a specific number (e.g. 400px ) or a range (using min-height and max-height ).
aspect-ratio Defines the width-to-height aspect ratio of the viewport
orientation The way the screen is oriented, such as tall ( portrait ) or wide ( landscape ) based on how the device is rotated. portrait

Источник

Оцените статью