Что такое медиа запросы в html
Перейти к содержимому

Что такое медиа запросы в html

  • автор:

CSS Media Queries

The @media rule, introduced in CSS2, made it possible to define different style rules for different media types.

Examples: You could have one set of style rules for computer screens, one for printers, one for handheld devices, one for television-type devices, and so on.

Unfortunately these media types never got a lot of support by devices, other than the print media type.

CSS3 Introduced Media Queries

Media queries in CSS3 extended the CSS2 media types idea: Instead of looking for a type of device, they look at the capability of the device.

Media queries can be used to check many things, such as:

  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution

Using media queries are a popular technique for delivering a tailored style sheet to desktops, laptops, tablets, and mobile phones (such as iPhone and Android phones).

Browser Support

The numbers in the table specifies the first browser version that fully supports the @media rule.

Property
@media 21.0 9.0 3.5 4.0 9.0

Media Query Syntax

A media query consists of a media type and can contain one or more expressions, which resolve to either true or false.

The result of the query is true if the specified media type matches the type of device the document is being displayed on and all expressions in the media query are true. When a media query is true, the corresponding style sheet or style rules are applied, following the normal cascading rules.

Unless you use the not or only operators, the media type is optional and the all type will be implied.

You can also have different stylesheets for different media:

CSS3 Media Types

Value Description
all Used for all media type devices
print Used for printers
screen Used for computer screens, tablets, smart-phones etc.
speech Used for screenreaders that "reads" the page out loud

Media Queries Simple Examples

One way to use media queries is to have an alternate CSS section right inside your style sheet.

The following example changes the background-color to lightgreen if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be pink):

Example

The following example shows a menu that will float to the left of the page if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the menu will be on top of the content):

Example

More Media Query Examples

For much more examples on media queries, go to the next page: CSS MQ Examples.

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.

Использование медиавыражений

Медиавыражения используются в тех случаях , когда нужно применить разные CSS-стили, для разных устройств по типу отображения (например: для принтера, монитора или смартфона), а также конкретных характеристик устройства (например: ширины окна просмотра браузера), или внешней среды (например: внешнее освещение). Учитывая огромное количество подключаемых к интернету устройств, медиавыражения являются очень важным инструментом при создании веб-сайтов и приложений, которые будут правильно работать на всех доступных устройствах, которые есть у ваших пользователей.

Медиа для разных типов устройств

Медиавыражения позволяют адаптировать страницу для различных типов устройств, таких как: принтеры, речевых браузеров, устройств Брайля, телевизоров и так далее. Например это правило для принтеров:

Вы также можете писать правила сразу для нескольких устройств. Например этот @media написан сразу для экранов и принтеров:

Список устройств вы можете найти перейдя по этой ссылке (en-US) . Но для задания более детальных и узконаправленных правил вам нужно просмотреть следующий раздел.

Узконаправленные @media

Media features (en-US) описывают некие характеристики определённого user agent, устройства вывода или окружения. Например, вы можете применить выбранные стили только для широкоэкранных мониторов, компьютеров с мышью, или для устройств, которые используются в условиях слабой освещённости. В примере ниже стили будут применены только когда основное устройство ввода пользователя (например мышь) будет расположено над элементами:

Многие медиавыражения представляют собой функцию диапазона и имеют префиксы «min-» или «max-«. Минимальное значение и максимальное значение условия, соответственно. Например этот CSS-код применяется только если ширина viewport меньше или равна 12450px:

Если вы создаёте медиавыражение без указания значения, вложенные стили будут использоваться до тех пор, пока значение функции не равно нулю. Например, этот CSS будет применяться к любому устройству с цветным экраном:

Если функция не применима к устройству, на котором работает браузер, выражения, включающие эту функцию, всегда ложны. Например, стили, вложенные в следующий запрос, никогда не будут использоваться, потому что ни одно речевое устройство не имеет формат экрана:

Дополнительные примеры медиавыражений, смотрите на справочной странице для каждой конкретной функции.

Создание комплексных медиавыражений

Иногда вы хотите создать медиавыражение, включающее в себя несколько условий. В таком случае применяются логические операторы: not , and , and only . Кроме того, вы можете объединить несколько медиавыражений в список через запятую; это позволяет применять одни и те же стили в разных ситуациях.

В прошлом примере мы видели, как применяется оператор and для группировки type и функции. Оператор and также может комбинировать несколько функций в одно медиавыражение. Между тем, оператор not отрицает медиавыражение, полностью инвертируя его значение. Оператор only работает тогда, когда применяется всё выражение, не позволяя старым браузерам применять стили.

Примечание: In most cases, the all media type is used by default when no other type is specified. However, if you use the not or only operators, you must explicitly specify a media type.

The and keyword combines a media feature with a media type or other media features. This example combines two media features to restrict styles to landscape-oriented devices with a width of at least 30 ems:

To limit the styles to devices with a screen, you can chain the media features to the screen media type:

comma-separated lists

You can use a comma-separated list to apply styles when the user’s device matches any one of various media types, features, or states. For instance, the following rule will apply its styles if the user’s device has either a minimum height of 680px or is a screen device in portrait mode:

Taking the above example, if the user had a printer with a page height of 800px, the media statement would return true because the first query would apply. Likewise, if the user were on a smartphone in portrait mode with a viewport height of 480px, the second query would apply and the media statement would still return true.

The not keyword inverts the meaning of an entire media query. It will only negate the specific media query it is applied to. (Thus, it will not apply to every media query in a comma-separated list of media queries.) The not keyword can’t be used to negate an individual feature query, only an entire media query. The not is evaluated last in the following query:

. so that the above query is evaluated like this:

. rather than like this:

As another example, the following media query:

. is evaluated like this:

The only keyword prevents older browsers that do not support media queries with media features from applying the given styles. It has no effect on modern browsers.

# Media Queries

If these conditions are met, the styles inside the media query will be active, and the background color of the page will be sky blue.

Media queries are applied dynamically. If on page load the conditions specified in the media query are met, the CSS will be applied, but will be immediately disabled should the conditions cease to be met. Conversely, if the conditions are initially not met, the CSS will not be applied until the specified conditions are met.

In our example, if the user’s view port width is initially greater than 720 pixels, but the user shrinks the browser’s width, the background color will cease to be sky blue as soon as the user has resized the view port to less than 720 pixels in width.

# mediatype

Media queries have an optional mediatype parameter. This parameter is placed directly after the @media declaration ( @media mediatype ), for example:

The above CSS code will give the DOM HTML element a white background color when being printed.

The mediatype parameter has an optional not or only prefix that will apply the styles to everything except the specified mediatype or only the specified media type, respectively. For example, the following code example will apply the style to every media type except print .

And the same way, for just showing it only on the screen, this can be used:

The list of mediatype can be understood better with the following table:

Media Type Description
all Apply to all devices
screen Default computers
print Printers in general. Used to style print-versions of websites
handheld PDA’s, cellphones and hand-held devices with a small screen
projection For projected presentation, for example projectors
aural Speech Systems
braille Braille tactile devices
embossed Paged braille printers
tv Television-type devices
tty Devices with a fixed-pitch character grid. Terminals, portables.

# Terminology and Structure

Media queries allow one to apply CSS rules based on the type of device / media (e.g. screen, print or handheld) called media type, additional aspects of the device are described with media features such as the availability of color or viewport dimensions.

# General Structure of a Media Query

# A Media Query containing a Media Type

# A Media Query containing a Media Type and a Media Feature

# A Media Query containing a Media Feature (and an implicit Media Type of "all")

# Width vs Viewport

When we are using "width" with media queries it is important to set the meta tag correctly. Basic meta tag looks like this and it needs to be put inside the <head> tag.

Why this is important?

Based on MDN’s definition "width" is

The width media feature describes the width of the rendering surface of the output device (such as the width of the document window, or the width of the page box on a printer).

What does that mean?

View-port is the width of the device itself. If your screen resolution says the resolution is 1280 x 720, your view-port width is "1280px".

More often many devices allocate different pixel amount to display one pixel. For an example iPhone 6 Plus has 1242 x 2208 resolution. But the actual viewport-width and viewport-height is 414 x 736. That means 3 pixels are used to create 1 pixel.

But if you did not set the meta tag correctly it will try to show your webpage with its native resolution which results in a zoomed out view (smaller texts and images).

# Media Queries for Retina and Non Retina Screens

Although this works only for WebKit based browsers, this is helpful:

Background Information

There are two types of pixels in the display. One is the logical pixels and the other is the physical pixels. Mostly, the physical pixels always stay the same, because it is the same for all the display devices. The logical pixels change based on the resolution of the devices to display higher quality pixels. The device pixel ratio is the ratio between physical pixels and logical pixels. For instance, the MacBook Pro Retina, iPhone 4 and above report a device pixel ratio of 2, because the physical linear resolution is double the logical resolution.

The reason why this works only with WebKit based browsers is because of:

  • The vendor prefix -webkit- before the rule.
  • This hasn’t been implemented in engines other than WebKit and Blink.

# Using Media Queries to Target Different Screen Sizes

Often times, responsive web design involves media queries, which are CSS blocks that are only executed if a condition is satisfied. This is useful for responsive web design because you can use media queries to specify different CSS styles for the mobile version of your website versus the desktop version.

# Use on link tag

This stylesheet is still downloaded but is applied only on devices with screen width larger than 600px.

# Media queries and IE8

(opens new window) are not supported at all in IE8 and below.

# A Javascript based workaround

To add support for IE8, you could use one of several JS solutions. For example, Respond

(opens new window) can be added to add media query support for IE8 only with the following code :

(opens new window) is another library that does the same thing. The code for adding that library to your HTML would be identical :

# The alternative

If you don’t like a JS based solution, you should also consider adding an IE<9 only stylesheet where you adjust your styling specific to IE<9. For that, you should add the following HTML to your code:

Note :

Technically it’s one more alternative: using CSS hacks

(opens new window) to target IE<9. It has the same impact as an IE<9 only stylesheet, but you don’t need a seperate stylesheet for that. I do not recommend this option, though, as they produce invalid CSS code (which is but one of several reasons why the use of CSS hacks is generally frowned upon today).

# Syntax
  • @media [not|only] mediatype and (media feature) < /_ CSS rules to apply _/ >
# Parameters
Parameter Details
mediatype (Optional) This is the type of media. Could be anything in the range of all to screen .
not (Optional) Doesn’t apply the CSS for this particular media type and applies for everything else.
media feature Logic to identify use case for CSS. Options outlined below.
Media Feature Details
aspect-ratio Describes the aspect ratio of the targeted display area of the output device.
color Indicates the number of bits per color component of the output device. If the device is not a color device, this value is zero.
color-index Indicates the number of entries in the color look-up table for the output device.
grid Determines whether the output device is a grid device or a bitmap device.
height The height media feature describes the height of the output device’s rendering surface.
max-width CSS will not apply on a screen width wider than specified.
min-width CSS will not apply on a screen width narrower than specified.
max-height CSS will not apply on a screen height taller than specified.
min-height CSS will not apply on a screen height shorter than specified.
monochrome Indicates the number of bits per pixel on a monochrome (greyscale) device.
orientation CSS will only display if device is using specified orientation. See remarks for more details.
resolution Indicates the resolution (pixel density) of the output device.
scan Describes the scanning process of television output devices.
width The width media feature describes the width of the rendering surface of the output device (such as the width of the document window, or the width of the page box on a printer).
Deprecated Features Details
device-aspect-ratio Deprecated CSS will only display on devices whose height/width ratio matches the specified ratio. This is a deprecated feature and is not guaranteed to work.
max-device-width Deprecated Same as max-width but measures the physical screen width, rather than the display width of the browser.
min-device-width Deprecated Same as min-width but measures the physical screen width, rather than the display width of the browser.
max-device-height Deprecated Same as max-height but measures the physical screen width, rather than the display width of the browser.
min-device-height Deprecated Same as min-height but measures the physical screen width, rather than the display width of the browser.
# Remarks

Media queries are supported in all modern browsers, including Chrome, Firefox, Opera, and Internet Explorer 9 and up.

It is important to note that the orientation media feature is not limited to mobile devices. It is based on the width and height of the viewport (not window or devices).

Landscape Mode is when the viewport width is larger than viewport height.

Portrait Mode is when the viewport height is larger than viewport width.

This usually translates to a desktop monitor being in landscape mode, but can it sometimes be portrait.

In most cases mobile devices will report their resolution and not their real pixel size which can differ due to pixel density. To force them to report their real pixel size add the following inside your head tag:

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

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.

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.

Using media queries

Media queries are commonly associated with CSS, but they can be used in HTML and JavaScript as well.

There are a few ways we can use media queries directly in HTML.

There’s the <link> element that goes right in the document <head> . 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 <link> element. As our guide to responsive images explains, we can use media queries on <source> element, which informs the <picture> 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 <style> element as well:

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.

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

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:

Then we can fire log to the console when that condition is matched:

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.

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.

Anatomy of a Media Query

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.

Syntax for CSS media queries.

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.

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

But screens aren’t the only type of media we can target, of course. We have a few, including:

  • 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 ). <length>
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 ). <length>
aspect-ratio Defines the width-to-height aspect ratio of the viewport <ratio>
orientation The way the screen is oriented, such as tall ( portrait ) or wide ( landscape ) based on how the device is rotated. portrait

Feature Summary Values Added
resolution Defines the target pixel density of the device <resolution>

Feature Summary Values Added
color Defines the color support of a device, expressed numerically as bits. So, a value of 12 would be the equivalent of a device that supports 12-bit color, and a value of zero indicates no color support. <integer>
color-index Defines the number of values the device supports. This can be a specific number (e.g. 10000 ) or a range (e.g. min-color-index: 10000 , max-color-index: 15000 ), just like width . <integer>
monochrome The number of bits per pixel that a device’s monochrome supports, where zero is no monochrome support. <integer>
color-gamut Defines the range of colors supported by the browser and device, which could be srgb , p3 or rec2020 srgb

Feature Summary Values Added
pointer Sort of like any-pointer but checks if the primary input mechanism is a pointer and, if so, how accurate it is (where coarse is less accurate, fine is more accurate, and none is no pointer). coarse

The spec references user agents, including TVs, that render video and graphics in two separate planes that each have their own characteristics. The following features describe those planes.

Feature Summary Values Added
scripting Checks whether the device allows scripting (i.e. JavaScript) where enabled allows scripting, iniital-only enabled

Feature Summary Values Added
prefers-reduced-motion Detects if the user’s system settings are set to reduce motion on the page, which is a great accessibility check. no-preference

Name Summary Removed
device-aspect-ratio The width-to-height aspect ratio of the output device Media Queries Level 4
device-height The height of the device’s surface that displays rendered elements Media Queries Level 4
device-width The width of the device’s surface that displays rendered elements Media Queries Level 4

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 types and features are matches, then do some stuff.

But we can use the and operator if we want to target screens within a range of widths:

or (or comma-separated)

We can also comma-separate features as a way of using an or operator to match different ones:

Perhaps we want to target devices by what they do not support or match. This declaration removes the body’s background color when the device is a printer and can only show one color.

Want to go deeper? Check out “CSS Media Queries: Quick Reference & Guide” from the DigitalOcean community for more examples that follow the syntax for media quieries.

Do you really need CSS media queries?

Media queries are a powerful tool in your CSS toolbox with exciting hidden gems. But if you accomodate your design to every possible situation you’ll end up with a codebase that’s too complex to maintain and, as we all know, CSS is like a bear cub: cute and inoffensive but when it grows it will eat you alive.

That’s why I recommend following Ranald Mace’s concept of Universal Design which is “the design of products to be usable by all people, to the greatest extent possible, without the need for adaptation or specialized design.”

In “Accessibility for Everyone” Laura Kalbag explains that the difference between accessible and universal design is subtle but important. An accessible designer would create a large door for people on a wheel chair to enter, while a universal designer would produce an entry that anyone would fit disregarding of their abilities.

I know that talking about universal design on the web is hard and almost sound utopian, but think about it, there are around 150 different browsers, around 50 different combinations of user preferences, and as we mentioned before more than 24000 different and unique Android devices alone.

This means that there are at least 18 million possible cases in which your content might be displayed. In the words of the fantastic Miriam Suzanne, “CSS out here trying to do graphic design of unknown content on an infinite and unknown canvas, across operating systems, interfaces, & languages. There’s no possible way for any of us to know what we’re doing.”

That’s why assuming is really dangerous, so when you design, develop and think about your products leave assumptions behind and use media queries to make sure that your content is displayed correctly in any contact and before any user.

Matching value ranges

Many of the media features outlined in the previous section — including width , height , color and color-index — can be prefixed with min- or max- to express minimum or maximum constraints. We’ve already seen these in use throughout many of the examples, but the point is that we can create a range of value to match instead of having to declare specific values.

In the following snippet, we’re painting the body’s background purple when the viewport width is wider than 30em and narrower than 80em. If the viewport width does not match that range of values, then it will fallback to white.

Media Queries Level 4 specifies a new and simpler syntax using less then ( < ), greater than ( > ) and equals ( = ) operators. So, that last example can be converted to the new syntax, like so:

Nesting and complex decision making

CSS allows you to nest at-rules or group statements using parentheses, making it possible to go as deep as we want to evaluate complex operations.

Be careful! even thought it’s possible to create powerful and complex expressions, you might end up with a very opinionated, hard to maintain query. As Brad Frost puts it: “The more complex our interfaces are, the more we have to think to maintain them properly.”

Many of the features added in Media Queries Level 4 are centered around accessibility.

prefers-reduced-motion detects if the user has the reduced motion preference activated to minimize the amount of movements and animations. It takes two values:

  • no-preference : Indicates that the user has made no preference known to the system.
  • reduce : Indicates that user has notified the system that they prefer an interface that minimizes the amount of movement or animation, preferably to the point where all non-essential movement is removed.

This preference is generally used by people who suffer from vestibular disorder or vertigo, where different movements result in loss of balance, migraine, nausea or hearing loss. If you ever tried to spin quickly and got dizzy, you know what it feels like.

In a fantastic article by Eric Bailey, he suggests stopping all animations with this code:

Popular frameworks like Bootstrap have this feature on by default. In my opinion there is no excuse not to use prefers-reduced-motion — just use it.

The prefers-contrast feature informs whether the user has chosen to increase or reduce contrast in their system preferences or the browser settings. It takes three values:

  • no-preference : When a user has made no preference known to the system. If you use it as a boolean it’ll evaluate false.
  • high : When a user has selected the option to display a higher level of contrast.
  • low : When a user has selected the option to display a lower level of contrast.

At the moment of writing this feature is not supported by any browser. Microsoft has done a non-standard earlier implementation with the -ms-high-contrast feature that works only on Microsoft Edge v18 or earlier (but not Chromium-based versions).

This example is increasing the contrast of a the class button from AA to AAA when the user has high contrast on.

The inverted-colors feature informs whether the user has chosen to invert the colors on their system preferences or the browser settings. Sometimes this option is used as an alternative to high contrast. It takes three values:

  • none : When colors are displayed normally
  • inverted : When a user has selected the option to invert colors

The problem with inverted colors is that it’ll also invert the colors of images and videos, making them look like x-ray images. By using a CSS invert filter you can select all images and videos and invert them back.

At the time of writing this feature is only supported by Safari.

Having a “dark mode” color scheme is something we’re seeing a lot more of these days, and thanks to the prefers-color-scheme feature, we can tap into a user’s system or browser preferences to determine whether we serve a “dark” or a “light” theme based on the ir preferences.

It takes two values:

  • light : When a user has selected that they prefer a light theme or has no active preferences
  • dark : When a user has selected a dark display in their settings

As Adhuham explains in the complete guide to Dark Mode there is way more to it than just changing the color of the background. Before you jump into doing dark mode remember that if you don’t have a very smart implementation strategy you might end up with a code base that’s really hard to maintain. CSS variables can do wonders for it but that’s a subject for another article.

What lies ahead?

Media Queries Level 5 is currently in Working Draft status, which means a lot can change between now and when it becomes a recommendation. But it includes interesting features that are worth mentioning because they open up new ways to target screens and adapt designs to very specific conditions.

User preference media features

Hey, we just covered these in the last section! Oh well. These features are exciting because they’re informed by a user’s actual settings, whether they are from the user agent or even at the operating system level.

Detecting a forced color palette

This is neat. Some browsers will limit the number of available colors that can be used to render styles. This is called “forced colors mode” and, if enabled in the browser settings, the user can choose a limited set of colors to use on a page. As a result, the user is able to define color combinations and contrasts that make content more comfortable to read.

The forced-colors feature allows us to detect if a forced color palette is in use with the active value. If matched, the browser must provide the required color palette through the CSS system colors. The browser is also given the leeway to determine if the background color of the page is light or dark and, if appropriate, trigger the appropriate prefers-color-scheme value so we can adjust the page.

Detecting the maximum brightness, color depth, and contrast ratio

Some devices (and browsers) are capable of super bright displays, rendering a wide range of colors, and high contrast ratios between colors. We can detect those devices using the dynamic-range feature, where the high keyword matches these devices and standard matches everything else.

We’re likely to see changes to this because, as of right now, there’s still uncertainty about what measurements constitute “high” levels of brightness and contrast. The browser may get to make that determination.

Video prefixed features

The spec talks about some screens, like TVs, that are capable of displaying video and graphics on separate “planes” which might be a way of distinguishing the video frame from other elements on the screen. As such, Media Queries Level 5 is proposing a new set of media features aimed at detecting video characteristics, including color gamut and dynamic range.

There are also proposals to detect video height, width and resolution, but the jury’s still out on whether those are the right ways to address video.

Browsers keep evolving and since by the time you are reading this post chances are that browser support for this feature might change, please check MDN updated browser compatibility table.

A note on container queries

Wouldn’t be cool if components could adapt themselves on their own size instead of the browser’s? That’s what the concept of CSS Container Queries is all about. We currently only have the browser screen to make those changes via media queries.

That’s unfortunate, as the viewport isn’t always a direct relationship to how big the element itself is. Imagine a widget that renders in many different contexts on a site: sometimes in a sidebar, sometimes in a full-width footer, sometimes in a grid with unknown columns.

This is the problem that container queries try to solve. Ideally we could adapt styles of an element according to the size of itself instead of of the size of the viewport. Chrome 105 released support for CSS Container Queries. Same deal with Safari 16.1. Firefox is all we’re really waiting at the time of writing to get broad support.

This browser support data is from Caniuse, which has more detail. A number indicates that browser supports the feature at that version and up.

Desktop
Chrome Firefox IE Edge Safari
106 110 No 106 16.0
Mobile / Tablet
Android Chrome Android Firefox Android iOS Safari
113 113 113 16.0

Let’s look at a bunch of media query examples. There are so many combinations of media types, features, and operators that the number of possibilities we could show would be exhaustive. Instead, we’ll highlight a handful based on specific media features.

Adjust layout at different viewport widths

This is the probably the most widely used media feature. It informs the width of the browser’s viewport including the scrollbar. It unlocked the CSS implementation of what Ethan Marcotte famously coined responsive design: a process by which a design responds to the size of the viewport using a combination of a fluid grid, flexible images, and responsive typesetting.

Later, Luke Wroblewski evolved the concept of responsive design by introducing the term mobile-first, encouraging designers and developers to start with the small-screen experience first then progressively enhance the experience as the screen width and device capabilities expand.

A mobile-first can usually be spotted by it’s use of min-width instead of max-width . If we start with min-width , we’re essentially saying, “hey, browser, start here and work up.” On the flip side, max-width is sort of like prioritizing larger screens.

One approach for defining breakpoints by width is using the dimensions of standard devices, like the exact pixel width of an iPhone. But there are many, many (many), many different phones, tables, laptops, and desktops. Looking at Android alone, there are more than 24,000 variations of viewport sizes, resolutions, operating systems, and browsers, as of August 2015.

So, while targeting the precise width of a specific device might be helpful for troubleshooting or one-off fixes, it’s probably not the most robust solution for maintaining a responsive architecture. This isn’t a new idea by any stretch. Brad Frost was already preaching the virtues of letting content — not devices — determine breakpoints in his post “7 habits of highly effective media queries” published back in 2013.

And even though media queries are still a valid tool to create responsive interfaces, there are many situations where it’s possible to avoid using width at all. Modern CSS allow us to create flexible layouts with CSS grid and flex that adapts our content to the viewport size without a need to add breakpoints. For example, here is a grid layout that adapts how many columns it will have without any media queries at all.

There are many articles about thinking beyond width, I wrote about it a few years ago and I recommend checking out Una Kravet’s Ten modern layouts in one line of CSS.

This example is pulled straight from our Guide to Dark Mode on the Web. The idea is that we can detect whether a user’s system settings are configured to light or dark mode using the prefers-color-scheme feature and then define an alternate set of colors for the rendered UI.

Combining this technique with CSS custom properties makes things even easier because they act like variables that we only need to define once, then use throughout the code. Need to swap colors? Change the custom property value and it updates everywhere. That’s exactly what prefers-color-scheme does. We define a set of colors as custom properties, then redefine them inside a media query using the prefer-color-scheme feature to change colors based on the user’s settings.

Detecting orientation, hover and motion on a responsive card gallery

This gallery is responsive without using the width feature.

It detects the orientation of the viewport. If it’s a portrait viewport, the sidebar will became a header; if it’s landscape it stays off to the side.

Using the pointer media feature, it decides if the main input device is coarse — like a finger — or fine — like a mouse cursor — to set the size of the clickable areas of the checkboxes.

Then, by using the hover media feature, the example checks if the device is capable of hovering (like a mouse cursor) and display a checkbox in each card.

The animations are removed when prefers-reduced-motion is set to reduce .

And did you notice something? We’re actually not using media queries for the actual layout and sizing of the cards! That’s handled using the minmax() function on the .container element to show how responsive design doesn’t always mean using media queries.

In short, this is a fully responsive app without ever measuring width or making assumptions.

Target an iPhone in landscape mode

The orientation media feature tests whether a device is rotated the wide way (landscape) or the tall way (portrait).

While media queries are unable to know exactly which device is being used, we can use the exact dimensions of a specific device. The snippet above is targets the iPhone X.

Apply a sticky header for large viewports

In the example above, we’re using height to detached fixed elements and avoid taking up too much screen real estate when the screen is too short. A horizontal navigation bar is in a fixed position when the screen is tall, but detaches itself on shorter screens.

Like the width feature, height detects the height of the viewport, including the scrollbar. Many of us browse the web on small devices with narrow viewports, making designing for different heights more relevant than ever. Anthony Colangelo describes how Apple uses the height media feature in a meaningful way to deal with the size of the hero image as the viewport’s height changes.

Responsive (fluid) typography

A font can look either too big or too small, depending on the size of the screen that’s showing it. If we’re working on a small screen, then chances are that we’ll want to use smaller type than what we’d use on a much larger screen.

The idea here is that we’re using the browser’s width to scale the font size. We set a default font size on the <html> that acts as the “small” font size, then set another font size using a media query that acts as the “large” font size. In the middle? We set the font size again, but inside another media query that calculates a size based on the browser width.

The beauty of this is that it allows the font size to adjust based on the browser width, but never go above or below certain sizes. However, there is a much simpler way to go about this that requires no media queries at all, thanks to newer CSS features, like min() , max() , and clamp() .

Provide bigger touch targets when devices have a course pointer

Have you ever visited a site that had super tiny buttons? Some of us have fat fingers making it tough to tap an object accurately without inadvertently tapping something else instead.

Sure, we can rely on the width feature to tell if we’re dealing with a small screen, but we can also detect if the device is capable of hovering over elements. If it isn’t then it’s probably a touch device, or perhaps a device that supports both, like the Microsoft Surface.

The demo above uses checkboxes as an example. Checkboxes can be a pain to tap on when viewing them on a small screen, so we’re increasing the size and not requiring a hover if the device is incapable of hover events.

Again, this approach isn’t always accurate. Check out Patrick Lauke’s thorough article that details potential issues working with hover , pointer , any-hover and any-pointer .

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *