Меню

Media query expected ошибка

Im doing a scss mixin for media query

@mixin breakpoints($min-width, $max-width, $media-type: false) {
  @if $media-type == true {
    @media $media-type and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  } @else {
    @media all and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  }
}

$media-type is false as default, if i dont want to specify it when calling mixin. If $media-type is passed in mixin then i want to that variable to be printed after @media. So if i include mixin @include breakpoints(400, 600, only screen), as result i want @media only screen and..

when i try to test my mixin on sassmeister, i get this error:

Invalid CSS after "    @media ": expected media query (e.g. print, screen, print and screen), was "$media-type and..."

what am i doing wrong?

asked Mar 3, 2016 at 18:41

riogrande's user avatar

I found out a way to do it to work without having to specify if statement for each media type.

@mixin breakpoints($min-width, $max-width, $media-type: false) {
  @if $media-type {
    @media #{$media-type} and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  } @else {
    @media all and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  }
}

the key was in #{$media-type}. now everything works, but i dont know how correct my solution is.

now i can call the mixin with

@include breakpoints(400, 600, only screen)

and

@include breakpoints(400, 600, 'only screen')

and

@include breakpoints(400, 600)

which will bring back the all keyword

answered Mar 3, 2016 at 19:14

riogrande's user avatar

riogranderiogrande

3491 gold badge4 silver badges22 bronze badges

2

Sass does not understand what you are trying to do when you pass back in the $media-type variable. You will need to set an if statement for each ‘media type’ like:

@mixin breakpoints($min-width, $max-width, $media-type: false) {
  @if $media-type == print {
    @media print and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  } @else {
    @media all and (min-width: $min-width) and (max-width: $max-width) {
      @content;
    }
  }
}

answered Mar 3, 2016 at 19:08

JordanBarber's user avatar

JordanBarberJordanBarber

2,0014 gold badges33 silver badges61 bronze badges

2

I’m trying to standardize the sizes of the devices on my scss, based on this:

/** Extra small devices (phones, 600px and down) */
$extra-small-evices: "screen and (max-width: 600px)",
/** Small devices (portrait tablets and large phones, 601px to 768px) */
$small-devices = 'screen and (min-width: 601px) and (max-width: 768px)',
/** Medium devices (landscape tablets, 769px to 991px) */
$medium-devices = 'screen and (min-width: 769px) and (max-width: 991px)',
/** Large devices (laptops/desktops, 992px to 1200px) */
$large-devices = 'screen and (min-width: 992px) and (max-width: 1200px)',
/** Extra large devices (large laptops and desktops, 1201px and up) */
$extra-large-devices = 'screen and (min-width: 1201px)'

After this, less say that I want to create a media query which the target is the small devices and medium devices:

@media $small-devices,
@media $medium-devices{
   ....
}

But I’m getting the following error on the @media $small-devices, line:

[scss] media query expected

Environment: Visual studio code, nodejs, angular 6, gulp,

Any one knows how no solve this?

В этой статье мы подробно рассмотрим, что такое медиа-запросы, как они работают и как их правильно использовать, в том числе и для создания адаптивного дизайна. Разберём конструкции @media, которые используются в Bootstrap.

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

Медиа-запросы (media queries) – это правила CSS, которые позволяют управлять стилями элементов в зависимости от значений технических параметров устройств. Иными словами, это конструкции, которые позволяют определять на основании некоторых условий какие стили необходимо использовать на веб-странице, а какие нет.

Медиа-запросы появились в спецификации CSS3 и на сегодняшний день поддерживаются всеми современными браузерами (Chrome 4+, Firefox 3.5+, IE 9+, Opera 9+, Safari 4+).

Поддержка браузерами CSS3 медиа-запросов (media queries)

Поддержка медиа-запросов в браузере IE8 осуществляется посредством подключения к странице скрипта «respond.js»:

<!-- Respond.js для IE8 (media queries) -->
<!-- Предупреждение: Respond.js не будет работать при просмотре страницы через file:// -->
<!--[if lt IE 9]>
  <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->

Медиа-запросы предназначены для создания адаптивных дизайнов. Адаптивный дизайн отличается от других тем, что он может «приспосабливаться» (видоизменяться) в зависимости от того, какую ширину экрана имеет устройство (браузер).

Но при создании адаптивных веб-страниц также необходимо обратить внимание на метатег viewport. Данный тег обеспечивает корректное отображение адаптивных дизайнов сайтов на экранах устройств, имеющих высокую плотность пикселей. Иными словами, он устанавливает соответствие между CSS и физическим разрешением веб-страницы.

Подключение метатега viewport к странице осуществляется так:

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

Синтаксис

Создание медиа-запроса начинается с ключевого слова @media после которого указывается одно или несколько условий. В качестве условия можно указывать тип устройства или требования к определённой характеристике. Требование к определённой характеристике записывается в круглых скобках.

Комбинирование нескольких условий выполняется с помощью логических операторов.

После составления @media, стили, указанные в нём, будут применяться только в том случае, когда итоговый результат вычисления условий является истинной.

Пример медиа-запроса с одним условием:

@media screen {
  /* стили будут применяться, когда условие истинно */
}

Пример медиа-запроса с комбинированием нескольких условий:

@media (min-width: 992px) and (max-width: 1199.98px) { ... }

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

  • all – для всех;
  • print – для принтеров и в режиме предварительного просмотра страницы перед печатью;
  • screen – для устройств с экранами;
  • speech – для программ чтения с экрана.

Например, этот @media только для экранов:

@media screen { ... }

А здесь для экранов и принтеров:

@media screen, print { ... }

Логические операторы

Логические операторы and, , (запятая), not и only предназначены для создания сложных медиа-запросов.

and

Оператор and используется для объединения нескольких условий. В этом случае их результат будет истинным, когда каждое из них будет истинным.

Например, следующий @media будет применяться только при выполнении всех трёх условий (это экран, width >= 1200px и ориентация landscape):

@media screen and (min-width: 1200px) and (orientation: landscape) { ... }

, (запятая)

Применение стилей, когда необходимо лишь выполнение одного из указанных условий, достигается посредством разделения их между собой с помощью , (запятой).

В этом примере стили будут применяться к странице в двух случаях. Когда width >= 544px или ориентация portrait.

@media (min-width: 544px), (orientation: landscape) { ... }

not

Ключевое слово not используется для отрицания.

При использовании not с and отрицание работает для всего медиа-запроса. При этом, когда указываем not необходимо обязательно задавать тип устройства.

Например, применим стили только в том случае, когда не (экран и width >= 411px и height >= 731px).

@media not screen and (min-width: 411px) and (min-height: 731px) { ... }

При использовании not в выражении с запятой он добавляет отрицание только для этой части.

Например, применим стили когда истинно следующее условие: не экран или не width >= 411px.

@media not screen, not (min-width: 411px) { ... }

only

Ключевое слово only предназначено для того, чтобы браузеры, которые не поддерживают CSS3 медиа-запросы их игнорировали. В настоящее время это уже не актуально, поэтому использовать only не нужно.

При составлении условия кроме типов устройств и логических операторов можно ещё задавать требования к определённым характеристикам, которые должен иметь браузер, устройство вывода, или окружение. В некоторых источниках характеристики называют медиа-функциями.

Каждая характеристика в @media должна быть заключена в круглые скобки.

При этом применяться стили указанные в @media будут также как раньше, т.е. только в том случае, когда результат вычисления всего выражения будет являться истиной.

width

Медиа-характеристика width позволяет задать условие на равенство ширины области просмотра определённому значению.

Например, применим CSS только для viewport с шириной 320px.

@media (width: 320px) { ... }

Для определения диапазона можно использовать min-width и max-width.

Например, @media для ширины viewport от 576px до 1200px:

@media (min-width: 576px) and (max-width: 1199.98px) { ... }

Для ширины больше 768px:

@media (min-width: 768px) { ... }

Если нужно меньше 1400px:

@media (max-width: 1399.98px) { ... }

height

Для задания условий в отношении высоты viewport можно использовать height, min-height и max-height.

Например, @media для высоты viewport больше 720px:

@media (min-height: 720px) { ... }

orientation

С помощью orientation можно установить те или иные стили в зависимости от того, в каком режиме (альбомном или портретном) отображается сайт.

Например, в зависимости от ориентации viewport будем отображать разные картинки:

@media (orientation: landscape) {
  .cover { background: url(bg-l.png) no-repeat; }
}

@media (orientation: portrait) {
  .cover { background: url(bg-p.png) no-repeat; }
}

aspect-ratio

Характеристики aspect-ration, min-aspect-ratio и max-aspect-ratio позволяют задавать стили в зависимости от соотношения сторон viewport.

/* Minimum aspect ratio */
@media (min-aspect-ratio: 9/16) {
  .header {
    background-color: #0dcaf0;
  }
}

/* Maximum aspect ratio */
@media (max-aspect-ratio: 16/9) {
  .header {
    background: #ffc107;
  }
}

/* Exact aspect ratio */
@media (aspect-ratio: 1/1) {
  .header {
    background: #6c757d;
  }
}

resolution

Характеристики resolution, min-resolution и max-resolution можно использовать, когда нужно задать стили в зависимости от плотности пикселей устройства.

Например, установим другой размер шрифта для устройств с плотностью пикселей на дюйм более 150:

/* Default */
p {
  font-size: 16px;
}

/* Minimum resolution */
@media (min-resolution: 150dpi) {
  p {
    font-size: 14px;
  }
}

Стили для печати страницы с плотностью пикселей больше 300dpi:

@media print and (min-resolution: 300dpi) { ... }

Медиа-запросы в <link> и @import

При подключении таблицы стилей можно с помощью атрибута media установить медиа-запросы и тем самым определить условия, когда они должны использоваться.

<link rel="stylesheet" media="screen and (max-width: 991.98px)" href="/assets/mobile.css">
<link rel="stylesheet" media="screen and (min-width: 992px)" href="/assets/desktop.css">

Кроме <link>, их также можно использовать в @import:

@import url(mobile.css) screen and (max-width: 991.98px);
@import url(desktop.css) screen and (min-width: 992px);

Медиа-запросы для Bootstrap 3

Организация media queries в порядке возрастания классов устройств xs, sm, md и lg (по умолчанию):

/* Устройства с очень маленьким экраном (смартфоны, меньше 768px) */
/* Стили CSS (по умолчанию) - для ширины viewport <768px */

/* Устроства с маленьким экраном (планшеты, 768px и выше) */
@media (min-width: 768px) {
/* Стили для устройств с шириной viewport, находящейся в диапазоне 768px - 991px */
}

/* Устройства со средним экраном (ноутбуки и компьютеры, 992px и выше) */
@media (min-width: 992px) {
  /* Стили для устройств с шириной viewport, находящейся в диапазоне 992px - 1199px */
}

/* Устройства с большим экраном (компьютеры, 1200px и выше) */
@media (min-width: 1200px) {
  /* Стили для устройств с шириной viewport >1200px */
}

Вышеприведённые запросы необходимо использовать только в указанном порядке.

Для того чтобы media запросы можно было применять в какой угодной последовательности, их необходимо расширить включив в них дополнительно выражение max-width. Это заставит их работать только в указанном диапазоне.

@media (max-width: 767px) {
  /* стили для xs-устройств */
}
@media (min-width: 768px) and (max-width: 991px) {
  /* стили для sm-устройств */
}
@media (min-width: 991px) and (max-width: 1199px) {
  /* стили для md-устройств */
}
@media (min-width: 1200px) {
  /* стили для lg-устройств */
}

Медиа-запросы для Bootstrap 4

Синтаксис медиа-запросов для Bootstrap 4, которые можно использовать только в следующем порядке (последовательного увеличения минимальной ширины viewport):

/* xs - устройства (до 576px) */
/* CSS для ширины, которая меньше 575px (включительно) */

/* sm-устройства (больше или равно 576px) */
@media (min-width: 576px) {
  /* CSS для: 576px <= ширины <= 767px */
}

/* md-устройства (больше или равно 768px) */
@media (min-width: 768px) {
  /* CSS для: 768px <= ширины <= 991px */
}

/* lg-устройства (больше или равно 992px) */
@media (min-width: 992px) {
  /* CSS для: 992px <= ширины <= 1119px */
}

/* xl-устройства (больше или равно 1200px) */
@media (min-width: 1200px) {
  /* CSS для: ширины >= 1200px */
}

Список media запросов для фреймворка Bootstrap 4, которые можно применять только в обратном порядке (в порядке убывания ширины области просмотра окна браузера):

/* xl-размер (>=1200px) */
/* CSS для >=1200px */

/* lg-размер (<=1199px) */
@media (max-width: 1199px) {
  /* CSS для ширины от 992px до 1199px */
}

/* md-размер (<=991px) */
@media (max-width: 991px) {
  /* CSS для ширины от 768px до 991px */
}

/* sm-размер (<=768px) */
@media (max-width: 767px) {
  /* CSS для ширины от 576px до 767px */
}

/* xs-размер (<=575px) */
@media (max-width: 575px) {
  /* CSS для ширины до 575px (включительно) */
}

Перечень медиа-запросов для Bootstrap 4, которые можно использовать в таблице стилей в любой последовательности:

/* xs (<=543px) */
@media (max-width: 575px) { ... }

/* sm (>=576 и <=767) */
@media (min-width: 576px) and (max-width: 767px) { ... }

/* md (>=768 и <=991) */
@media (min-width: 768px) and (max-width: 991px) { ... }

/* lg (>=992 и <=1199) */
@media (min-width: 992px) and (max-width: 1199px) { ... }

/* xl (>=1200) */
@media (min-width: 1200px) { ... }

Код JavaScript, учитывающий параметры устройств

Наиболее простой способ создания кода JavaScript, учитывающий параметры устройств (аналогично CSS медиа-запросам), осуществляется с помощью метода matchMedia объекта window.

Осуществляется это следующим образом:

// например, проверим, соответствует ли указанный медиа-запрос (screen and (max-width: 543px)) устройству
// результат проверки можно получить с помощью свойства matches (true или false)
if (window.matchMedia('screen and (max-width: 543px)').matches) {
  // ... действия, если устройство отвечает медиа-запросу
} else {
  // ... действия, если устройство не соответствует значениям медиа-запроса
}

Например, эту возможность можно применить для асинхронной загрузки картинок в зависимости от того какой размер viewport имеет устройство (браузер).

Метод matchMedia не поддерживается Internet Explorer 9 и другими старыми браузерами. Для того чтобы обеспечить эту функциональность в старых браузерах можно воспользоваться методом mq библиотеки Modernizr.

Поддержка браузерами метода matchMedia (JavaScript)

if (Modernizr.mq('(max-width: 767px)')) {
  // ... действия, если устройство соответствует указанному медиа-условию
} else {
  // ... действия, если устройство не отвечает заданному медиа-условию
}

@alastc

Running Sass on an imported file that includes this line:

Sass reports:
error media-queries.sass (Line 8: Invalid CSS after «screen «: expected media query list, was «{«)

I’m pretty sure that’s valid though, you don’t have to include size or other terms, like the second example here: http://www.w3.org/TR/css3-mediaqueries/

@Snugug

I’m not sure what version of Sass you’re running, but using both Sass 3.2.12 and Sass 3.3.rc.2, the following compiles absolutely fine:

@media screen {
  .foo {
    content: bar;
  }
}

@alastc

3.2.12, but perhaps it makes a difference that it is in an import? I moved my media queres into another file (media-queries.sass) and imported that into the main file. Then I get the errors.

I took the error message too literally though, it doesn’t matter whether there are ‘and’ conditions, it seems to matter they are in an import though.

@Snugug

Having them in an imported file should not make a difference and does not make a difference when tested. My suggestion is to build a reduced example and add back in code until you find your error; I’m willing to bet you have a syntax error somewhere, not that @media screen doesn’t work.

@nex3

I’m closing this, but I’ll re-open if you can provide a file or files that can consistently reproduce the error.

@alastc

Has the nature of ‘watch’ changed when I wasn’t looking? A sass file of just this:

Then:
# sass —watch test.sass:test.css

Gives me:

error test.sass (Line 2: Invalid CSS after «0»: expected expression (e.g. 1px, bold), was «;»)

Is there a forum somewhere? This is really odd, it is CSS that’s working fine in the full SASS stylesheet. Need somewhere to ask questions…

@nex3

That’s SCSS syntax, but your file uses the extension .sass, so Sass is trying to interpret it as the indented syntax and failing. Could that also be your problem with the media query?

@alastc

Ah, yes, that’s why everything seems to be wrong when I import that.

Sorry, I have never used the indented syntax, so I have no idea why I put .sass on that!

Abstract

HTML4 and CSS2 currently support media-dependent style sheets tailored
for different media types. For example, a document may use
sans-serif fonts when displayed on a screen and serif fonts when printed.
screen’ and ‘print’ are two media types that have been defined.
Media queries extend the functionality of media types by allowing
more precise labeling of style sheets.

A media query consists of a media type and zero or more expressions that
check for the conditions of particular media features. Among the
media features that can be used in media queries are ‘width’, ‘height’, and ‘color’. By using media queries, presentations can
be tailored to a specific range of output devices without changing the
content itself.

Status of this Document

This section describes the status of this document at the time of its publication. A list of current W3C publications and the latest revision of this technical report can be found in the W3C technical reports index at https://www.w3.org/TR/.

This document was published by the
CSS Working Group
as a Recommendation using the
Recommendation track.
It includes proposed corrections.

A W3C Recommendation is a specification that, after extensive consensus-building, is endorsed by W3C and its Members, and has commitments from Working Group members to royalty-free licensing for implementations.

W3C recommends the wide deployment of this specification as a standard for the Web.

Please send feedback
by filing issues in GitHub (preferred),
including the spec code “mediaqueries-3” in the title, like this:
“[mediaqueries-3] …summary of comment…”.
All issues and comments are archived.
Alternately, feedback can be sent to the (archived) public mailing list www-style@w3.org.
Comments are due by 5 June 2022.

This document is governed by the 2 November 2021 W3C Process Document.

This document was produced by a group operating under the W3C Patent Policy.
W3C maintains a public list of any patent disclosures made in
connection with the deliverables of the group; that page also includes
instructions for disclosing a patent. An individual who has actual
knowledge of a patent which the individual believes contains Essential
Claim(s) must disclose the information in accordance with section 6 of the
W3C Patent Policy.

1. Background

(This section is not normative.)

HTML4 [HTML401]
and CSS2 [CSS21]
currently support media-dependent style sheets tailored for different
media types. For example, a document may use different style sheets for
screen and print. In HTML4, this can be written as:

<link rel="stylesheet" type="text/css" media="screen" href="sans-serif.css">
<link rel="stylesheet" type="text/css" media="print" href="serif.css">

Inside a CSS style sheet, one can declare that sections apply to certain
media types:

@media screen {
  * { font-family: sans-serif }
}

The ‘print’ and ‘screen’ media types are defined in HTML4. The
complete list of media types in HTML4 is: ‘aural’, ‘braille’, ‘handheld’, ‘print’, ‘projection’, ‘screen’, ‘tty’,
tv’. CSS2 defines the same list,
deprecates ‘aural’ and adds
embossed’ and ‘speech’. Also, ‘all’ is used to indicate that the style sheet
applies to all media types.

Media-specific style sheets are supported by several user agents. The
most commonly used feature is to distinguish between ‘screen’ and ‘print’.

There have been requests for ways to describe in more detail what type
of output devices a style sheet applies to. Fortunately HTML4 foresaw
these requests and defined a forward-compatible syntax for media types.
Here is a quote from HTML4,
section 6.13:

Future versions of HTML may introduce new values and may allow
parameterized values. To facilitate the introduction of these extensions,
conforming user agents must be able to parse the media
attribute value as follows:

  1. The value is a comma-separated list of entries. For example,
    media="screen, 3d-glasses, print and resolution > 90dpi"

    is mapped to:

    "screen"
    "3d-glasses"
    "print and resolution > 90dpi"
  2. Each entry is truncated just before the first character that isn’t a
    US ASCII letter [a-zA-Z] (Unicode decimal 65-90, 97-122), digit [0-9]
    (Unicode hex 30-39), or hyphen (45). In the example, this gives:

    "screen"
    "3d-glasses"
    "print"

Media queries, as described in this specification, build on the
mechanism outlined in HTML4. The syntax of media queries fit into the
media type syntax reserved in HTML4. The media
attribute of HTML4 also exists in XHTML and generic XML. The same syntax
can also be used inside in the ‘@media
and ‘@import’ rules of CSS.

However, the parsing rules for media queries are incompatible with those
of HTML4 so that they are consistent with those of media queries used in
CSS.

Newer versions of HTML [HTML]
reference the Media Queries specification
directly and thus updates the rules for HTML.

A media query consists of a media type and zero or more expressions that check for the
conditions of particular media
features
.

Statements regarding media queries in this section assume the syntax section is followed. Media queries that do not
conform to the syntax are discussed in the error
handling section. I.e. the syntax takes precedence over requirements
in this section.

Here is a simple example written in HTML:

<link rel="stylesheet" media="screen and (color)" href="example.css" />

This example expresses that a certain style sheet
(example.css) applies to devices of a certain media type
(‘screen’) with certain feature (it
must be a color screen).

Here the same media query written in an @import-rule in CSS:

@import url(color.css) screen and (color);

A media query is a logical expression that is either true or false. A
media query is true if the media type of the media query matches the media
type of the device where the user agent is running (as defined in the
«Applies to» line), and all expressions in the media query are true.

A shorthand syntax is offered for media queries that apply to all media
types; the keyword ‘all’ can be left
out (along with the trailing ‘and’).
I.e. if the media type is not explicitly given it is ‘all’.

I.e. these are identical:

@media all and (min-width:500px) { … }
@media (min-width:500px) { … }

As are these:

@media (orientation: portrait) { … }
@media all and (orientation: portrait) { … }

Several media queries can be combined in a media query list. A
comma-separated list of media queries. If one or more of the media queries
in the comma-separated list are true, the whole list is true, and
otherwise false. In the media queries syntax, the comma expresses a
logical OR, while the ‘and’ keyword
expresses a logical AND.

Here is an example of several media queries in a comma-separated list
using the an @media-rule in CSS:

@media screen and (color), projection and (color) { … }

If the media query list is empty (i.e. the declaration is the empty
string or consists solely of whitespace) it evaluates to true.

I.e. these are equivalent:

@media all { … }
@media { … }

The logical NOT can be expressed through the ‘not’ keyword. The presence of the keyword
not’ at the beginning of the media
query negates the result. I.e., if the media query had been true without
the ‘not’ keyword it will become false,
and vice versa. User agents that only support media types (as described in
HTML4) will not recognize the ‘not
keyword and the associated style sheet is therefore not applied.

<link rel="stylesheet" media="not screen and (color)" href="example.css" />

The keyword ‘only’ can also be used
to hide style sheets from older user agents. User agents must process
media queries starting with ‘only’ as
if the ‘only’ keyword was not present.

<link rel="stylesheet" media="only screen and (color)" href="example.css" />

The media queries syntax can be used with HTML, XHTML, XML [XMLSTYLE] and the
@import and @media rules of CSS.

Here is the same example written in HTML, XHTML, XML, @import and
@media:

<link media="screen and (color), projection and (color)" rel="stylesheet" href="example.css">
<link media="screen and (color), projection and (color)" rel="stylesheet" href="example.css" />
<?xml-stylesheet media="screen and (color), projection and (color)" rel="stylesheet" href="example.css" ?>
@import url(example.css) screen and (color), projection and (color);
@media screen and (color), projection and (color) { … }

The [XMLSTYLE] specification has not
yet been updated to use media queries in the media
pseudo-attribute.

If a media feature does not apply to the device where the UA is running,
expressions involving the media feature will be false.

The media feature ‘device-aspect-ratio’ only applies to visual
devices. On an aural device, expressions involving ‘device-aspect-ratio’ will therefore always be
false:

<link rel="stylesheet" media="aural and (device-aspect-ratio: 16/9)" href="example.css" />

Expressions will always be false if the unit of measurement does not
apply to the device.

The ‘px’ unit does not apply to
speech’ devices so the following
media query is always false:

<link rel="stylesheet" media="speech and (min-device-width: 800px)" href="example.css" />

Note that the media queries in this example would have been true if the
keyword ‘not’ had been added to the
beginning of the media query.

To avoid circular dependencies, unless another feature explicitly
specifies that it affects the resolution of Media Queries, it is not necessary to apply the style
sheet in order to evaluate expressions. For example, the aspect ratio of a
printed document may be influenced by a style sheet, but expressions
involving ‘device-aspect-ratio’ will be
based on the default aspect ratio of the user agent.

User agents are expected, but not required, to re-evaluate
and re-layout the page in response to changes in the user environment, for
example if the device is tilted from landscape to portrait mode.

3. Syntax

The media query syntax is described in terms of the CSS2 grammar. As such,
rules not defined here are defined in CSS2. The
media_query_list production defined below replaces the
media_list production from CSS2. [CSS21]

media_query_list
 : S* [media_query [ ',' S* media_query ]* ]?
 ;
media_query
 : [ONLY | NOT]? S* media_type S* [ AND S* expression ]*
 | expression [ AND S* expression ]*
 ;
media_type
 : IDENT
 ;
expression
 : '(' S* media_feature S* [ ':' S* expr ]? ')' S*
 ;
media_feature
 : IDENT
 ;

COMMENT tokens, as defined by CSS2, do not occur in the grammar (to keep
it readable), but any number of these tokens may appear anywhere between
other tokens. [CSS21]

The following new definitions are introduced:

L  l|\0{0,4}(4c|6c)(rn|[ trnf])?|\l
Y  y|\0{0,4}(59|79)(rn|[ trnf])?|\y

The following new tokens are introduced:

{O}{N}{L}{Y}      {return ONLY;}
{N}{O}{T}         {return NOT;}
{A}{N}{D}         {return AND;}
{num}{D}{P}{I}    {return RESOLUTION;}
{num}{D}{P}{C}{M} {return RESOLUTION;}

RESOLUTION is to be added to the CSS2 term
production.

CSS style sheets are generally ASCII
case-insensitive, and this is also the case for media queries.

In addition to conforming to the syntax, each media query needs to use
media types and media features according to their respective specification
in order to be considered conforming.

Only the first media query is conforming in the example below because
the «example» media type does not exist.

@media all { body { background:lime } }
@media example { body { background:red } }

3.1. Error Handling

For media queries that are not conforming user agents need to follow the
rules described in this section.

Proposed Correction 1:
Clarify that the keywords ‘not’, ‘and’, ‘only’, and ‘or’ should not be treated as unknown media types,
but as syntax errors when used in place of media types.

The reasoning for this change can be found in the minutes of the 2013-05-30 CSS WG teleconference
and in the emails referenced therefrom.

This change has tests
Tests for this change have been added to WPT.
The results can be viewed at wpt.fyi.

  • Unknown media types. Unknown media types evaluate to
    false. Effectively, they are treated identically to known media types
    that do not match the media type of the device.
    However, an exception is made for media types ‘not’, ‘and’, ‘only’, and ‘or’.
    Even though they do match the IDENT production,
    they must not be treated as unknown media types,
    but rather trigger the malformed query clause.

    The media query «unknown» will evaluate to false, unless
    unknown is actually a supported media type. Similarly,
    «not unknown» will evaluate to true.

    The following is a malformed media query because it uses ‘only’ and ‘or’ as media types.

    @media only and or { … }

    Unknown media types are distinct from media types that do
    not actually match the IDENT production. Those fall under the malformed
    media query clause.

  • Unknown media features. User agents are to represent
    a media query as «not all» when one of the specified media
    features is not known.

    <link rel="stylesheet" media="screen and (max-weight: 3kg) and (color), (color)" href="example.css" />

    In this example, the first media query will be represented as
    «not all» and evaluate to false and the second media query
    is evaluated as if the first had not been specified, effectively.

    @media (min-orientation:portrait) { … }

    Is represented as «not all» because the ‘orientation’ feature does not accept the
    min-’ prefix.

  • Unknown media feature values. As with unknown media
    features, user agents are to represent a media query as «not
    all
    » when one of the specified media feature values is not known.

    The media query (color:20example) specifies an unknown
    value for the ‘color’ media feature
    and is therefore represented as «not all«.

    This media query is represented as «not all» because
    negative lengths are not allowed for the ‘width’ media feature:

    @media (min-width: -100px) { … }

  • Malformed media query. User agents are to handle
    unexpected tokens encountered while parsing a media query by reading
    until the end of the media query, while observing the rules for
    matching pairs of (), [], {}, «», and », and correctly
    handling escapes. Media queries with unexpected tokens are represented
    as «not all«. [CSS21]

    @media (example, all,), speech { /* only applicable to speech devices */ }
    @media &test, screen           { /* only applicable to screen devices */ }

    The following is an malformed media query because having no space
    between ‘and’ and the expression is
    not allowed. (That is reserved for the functional notation syntax.)

    @media all and(color) { … }

    Media queries are expected to follow the error handling rules of the
    host language as well.

    @media test;,all { body { background:lime } }

    … will not apply because the semicolon terminates the
    @media rule in CSS.

Syntactically, media features resemble CSS properties: they have names
and accept certain values. There are, however, several important
differences between properties and media features:

  • Properties are used in declarations to give information about
    how to present a document. Media features are used in
    expressions to describe requirements of the output device.

  • Most media features accept optional ‘min-’ or ‘max-
    prefixes to express «greater or equal to» and «smaller or equal to»
    constraints. This syntax is used to avoid «<» and «>» characters
    which may conflict with HTML and XML. Those media features that accept
    prefixes will most often be used with prefixes, but can also be used
    alone.

  • Properties always require a value to form a declaration. Media
    features, on the other hand, can also be used without a value. For a
    media feature feature, (feature) will
    evaluate to true if (feature:x) will
    evaluate to true for a value x other than zero or zero
    followed by a unit identifier (i.e., other than 0,
    0px, 0em, etc.). Media features that are
    prefixed by min/max cannot be used without a value. When a media feature
    prefixed with min/max is used without a value it makes the media query
    malformed.

  • Properties may accept more complex values, e.g., calculations that
    involve several other values. Media features only accept single values:
    one keyword, one number, or a number with a unit identifier. (The only
    exceptions are the ‘aspect-ratio’ and
    device-aspect-ratio’ media features.)

For example, the ‘color’ media
feature can form expressions without a value (‘(color)’), or with a value (‘(min-color: 1)’).

This specification defines media features usable with visual
and tactile devices. Similarly, media features can be defined for aural
media types.

4.1. width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘width’ media feature describes
the width of the targeted display area of the output device. For
continuous media, this is the width of the viewport (as described by CSS2,
section 9.1.1 [CSS21]) including the size of a
rendered scroll bar (if any). For paged media, this is the width of the
page box (as described by CSS2, section 13.2 [CSS21]).

A specified <length> cannot be negative.

For example, this media query expresses that the style sheet is usable
on printed output wider than 25cm:

<link rel="stylesheet" media="print and (min-width: 25cm)" href="http://…" />

This media query expresses that the style sheet is usable on devices
with viewport (the part of the screen/paper where the document is
rendered) widths between 400 and 700 pixels:

@media screen and (min-width: 400px) and (max-width: 700px) { … }

This media query expresses that style sheet is usable on screen and
handheld devices if the width of the viewport is greater than 20em.

@media handheld and (min-width: 20em),
  screen and (min-width: 20em) { … }

The ‘em’ value is relative to the
initial value of ‘font-size’.

4.2. height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘height’ media feature describes
the height of the targeted display area of the output device. For
continuous media, this is the height of the viewport including the size of
a rendered scroll bar (if any). For paged media, this is the height of the
page box.

A specified <length> cannot be negative.

4.3. device-width

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘device-width’ media feature
describes the width of the rendering surface of the output device. For
continuous media, this is the width of the screen. For paged media, this
is the width of the page sheet size.

A specified <length> cannot be negative.

@media screen and (device-width: 800px) { … }

In the example above, the style sheet will apply only to screens that
currently displays exactly 800 horizontal pixels. The ‘px’ unit is of the logical kind, as described in
the Units section.

4.4. device-height

Value: <length>
Applies to: visual and tactile media types
Accepts min/max prefixes: yes

The ‘device-height’ media feature
describes the height of the rendering surface of the output device. For
continuous media, this is the height of the screen. For paged media, this
is the height of the page sheet size.

A specified <length> cannot be negative.

<link rel="stylesheet" media="screen and (device-height: 600px)" />

In the example above, the style sheet will apply only to screens that
have exactly 600 vertical pixels. Note that the definition of the
px’ unit is the same as in other
parts of CSS.

4.5. orientation

Value: portrait |
landscape
Applies to: bitmap media types
Accepts min/max prefixes: no

The ‘orientation’ media feature is
portrait’ when the value of the
height’ media feature is greater than
or equal to the value of the ‘width
media feature. Otherwise ‘orientation
is ‘landscape’.

@media all and (orientation:portrait) { … }
@media all and (orientation:landscape) { … }

4.6. aspect-ratio

Value: <ratio>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘aspect-ratio’ media feature is
defined as the ratio of the value of the ‘width’ media feature to the value of the
height’ media feature.

4.7.
device-aspect-ratio

Value: <ratio>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘device-aspect-ratio’ media
feature is defined as the ratio of the value of the ‘device-width’ media feature to the value of the
device-height’ media feature.

For example, if a screen device with square pixels has 1280 horizontal
pixels and 720 vertical pixels (commonly referred to as «16:9»), the
following Media Queries will all match the device:

@media screen and (device-aspect-ratio: 16/9) { … }
@media screen and (device-aspect-ratio: 32/18) { … }
@media screen and (device-aspect-ratio: 1280/720) { … }
@media screen and (device-aspect-ratio: 2560/1440) { … }

4.8. color

Value:
<integer>
Applies to: visual media types
Accept min/max prefixes: yes

The ‘color’ media feature describes
the number of bits per color component of the output device. If the device
is not a color device, the value is zero.

A specified <integer> cannot be negative.

For example, these two media queries express that a style sheet applies
to all color devices:

@media all and (color) { … }
@media all and (min-color: 1) { … }

This media query expresses that a style sheet applies to color devices
with 2 or more bits per color component:

@media all and (min-color: 2) { … }

If different color components are represented by different number of
bits, the smallest number is used.

For instance, if an 8-bit color system represents the red component
with 3 bits, the green component with 3 bits and the blue component with
2 bits, the ‘color’ media feature will
have a value of 2.

In a device with indexed colors, the minimum number of bits per color
component in the lookup table is used.

The described functionality is only able to describe color
capabilities at a superficial level. If further functionality is required,
RFC2531 [RFC2531]
provides more specific media features which may be supported at a later
stage.

4.9. color-index

Value:
<integer>
Applies to: visual media types
Accepts min/max prefixes: yes

The ‘color-index’ media feature
describes the number of entries in the color lookup table of the output
device. If the device does not use a color lookup table, the value is
zero.

A specified <integer> cannot be negative.

For example, here are two ways to express that a style sheet applies to
all color index devices:

@media all and (color-index) { … }
@media all and (min-color-index: 1) { … }

This media query expresses that a style sheet applies to a color index
device with 256 or more entries:

<?xml-stylesheet media="all and (min-color-index: 256)"
  href="http://www.example.com/…" ?>

4.10. monochrome

Value:
<integer>
Applies to: visual media types
Accepts min/max prefixes: yes

The ‘monochrome’ media feature
describes the number of bits per pixel in a monochrome frame buffer. If
the device is not a monochrome device, the output device value will be 0.

A specified <integer> cannot be negative.

For example, here are two ways to express that a style sheet applies to
all monochrome devices:

@media all and (monochrome) { … }
@media all and (min-monochrome: 1) { … }

Express that a style sheet applies to monochrome devices with more than
2 bits per pixels:

@media all and (min-monochrome: 2) { … }

Express that there is one style sheet for color pages and another for
monochrome:

<link rel="stylesheet" media="print and (color)" href="http://…" />
<link rel="stylesheet" media="print and (monochrome)" href="http://…" />

4.11. resolution

Value:
<resolution>
Applies to: bitmap media types
Accepts min/max prefixes: yes

The ‘resolution’ media feature
describes the resolution of the output device, i.e. the density of the
pixels. When querying devices with non-square pixels, in ‘min-resolution’ queries the least-dense dimension
must be compared to the specified value and in ‘max-resolution’ queries the most-dense dimensions
must be compared instead. A ‘resolution’ (without a «min-» or «max-» prefix)
query never matches a device with non-square pixels.

For printers, this corresponds to the screening resolution (the
resolution for printing dots of arbitrary color).

For example, this media query expresses that a style sheet is usable on
devices with resolution greater than 300 dots per inch:

@media print and (min-resolution: 300dpi) { … }

This media query expresses that a style sheet is usable on devices with
resolution greater than 118 dots per centimeter:

@media print and (min-resolution: 118dpcm) { … }

4.12. scan

Value: progressive |
interlace
Applies to: «tv» media types
Accepts min/max prefixes: no

The ‘scan’ media feature describes
the scanning process of «tv» output devices.

For example, this media query expresses that a style sheet is usable on
tv devices with progressive scanning:

@media tv and (scan: progressive) { … }

4.13. grid

Value:
<integer>
Applies to: visual and tactile media types
Accepts min/max prefixes: no

The ‘grid’ media feature is used to
query whether the output device is grid or bitmap. If the output device is
grid-based (e.g., a «tty» terminal, or a phone display with only one fixed
font), the value will be 1. Otherwise, the value will be 0.

Only 0 and 1 are valid values. (This includes -0.) Thus everything else
creates a malformed media query.

Here are two examples:

@media handheld and (grid) and (max-width: 15em) { … }
@media handheld and (grid) and (max-device-height: 7em) { … }

5. Values

This specification also introduces two new values.

The <ratio> value is a positive (not zero or negative) <integer>
followed by optional whitespace, followed by a solidus (‘/’), followed by optional whitespace, followed by a
positive <integer>.

The <resolution> value is a positive <number> immediately followed
by a unit identifier (‘dpi’ or
dpcm’).

Whitespace, <integer>, <number> and other values used by this
specification are the same as in other parts of CSS, normatively defined
by CSS 2.1. [CSS21]

6. Units

The units used in media queries are the same as in other parts of CSS.
For example, the pixel unit represents CSS pixels and not physical pixels.

Relative units in media queries are based on the initial value, which
means that units are never based on results of declarations. For example,
in HTML, the ‘em’ unit is relative to
the initial value of ‘font-size’.

6.1. Resolution

The ‘dpi’ and ‘dpcm’ units describe the resolution of an output
device, i.e., the density of device pixels. Resolution unit identifiers
are:

dpi

dots per CSS ‘inch

dpcm

dots per CSS ‘centimeter

In this specification, these units are only used in the ‘resolution’ media feature.

7. Changes

7.1. Changes Since the 19 June 2012
Recommendation

Proposed Corrections were introduced:

  • Proposed Correction 1 in Section 3.1:
    Clarify that the keywords ‘not’, ‘and’, ‘only’, and ‘or’ should not be treated as unknown media types,
    but as syntax errors when used in place of media types.

A handful of editorial and markup corrections were also made:

  • Section 2: Dropped a redundant attribute in an example.
    <link rel="stylesheet" media="screen and (color), projection and (color)" rel="stylesheet" href="example.css">
    <link rel="stylesheet" media="screen and (color), projection and (color)" rel="stylesheet" href="example.css" />
  • Section 2: Adjusted a sentence to make it easier for other specifications to extend this one.

    To avoid circular dependencies, it is neverunless another feature explicitly specifies that it affects the resolution of Media Queries, it is not necessary to apply the style sheet in order to evaluate expressions.

  • Section 3: Used a more precise term to characterize the syntax of css,
    in a descriptive (rather than prescriptive) sentence.

    CSS style sheets are generally case-insensitive
    ASCII case-insensitive,
    and this is also the case for media queries.

    The veracity of this claim is validated by a test.

  • Section 4.13: Corrected a syntax error in an example.
    @media handheld and (grid) and (device-max-heightmax-device-height: 7em) { … }
  • Bibliographical references have been updated to point to the latest versions.
  • Various links throughout the specification were updated from http to https.

7.2. Changes Since the 27 July
2010 Candidate Recommendation

The following changes were made to this specification since the 27 July
2010 Candidate Recommendation:

  • Section 4.11: Clarified the meaning of
    resolution in the case of printers, for which the meaning of dots was
    ambiguous.

    For printers, this corresponds to the screening resolution (the
    resolution for printing dots of arbitrary color).

  • Section 6.1: Made it explicit that the
    inch’ and ‘cm’ mentioned are the CSS units, not the physical
    ones.

    dpi

    dots per CSS ‘inch’inch

    dpcm

    dots per CSS ‘centimeter’cm
  • Section 4.1: Adjust mistaken non normative
    wording to match correct normative wording from Section
    6.

    The ‘em’ value is relative to the
    font size of the root elementinitial value of
    ‘font-size’..

  • Section 6: Clarify that units are never based on
    the results of declarations.

    Relative units in media queries are based on the initial value,
    which means that units are never based on results of
    declarations. For example, in HTML, the ‘em’ unit is relative to the initial value of
    font-size’.

Acknowledgments

This specification is the product of the W3C Working Group on Cascading
Style Sheets.

Comments from Björn Höhrmann, Christoph Päper, Chris
Lilley, Simon Pieters, Rijk van Geijtenbeek, Sigurd Lerstad, Arve
Bersvendsen, Susan Lesch, Philipp Hoschka, Roger Gimson, Steven Pemberton,
Simon Kissane, Melinda Grant, and L. David Baron improved this
specification.

References

Normative references

[CSS21]

Bert Bos; et al. Cascading Style
Sheets Level 2 Revision 1 (CSS 2.1) Specification.
7 June
2011. W3C Recommendation. URL: http://www.w3.org/TR/2011/REC-CSS2-20110607

Other references

[HTML401]

Dave Raggett; Arnaud Le Hors; Ian Jacobs. HTML 4.01
Specification.
24 December 1999, superseded 27 March 2018. W3C Recommendation. URL: https://www.w3.org/TR/2018/SPSD-html401-20180327/
[HTML]

Anne van Kesteren; et al. HTML
Standard
. Living Standard. URL: https://html.spec.whatwg.org/multipage/
[RFC2531]

G. Klyne; L. McIntyre. Content Feature Schema
for Internet Fax.
March 1999. Internet RFC 2531. URL: http://www.ietf.org/rfc/rfc2531.txt
[XMLSTYLE]

James Clark; Simon Pieters; Henry S. Thompson Associating Style Sheets
with XML documents 1.0 (Second Edition)
28 October 2010. W3C
Recommendation. URL: http://www.w3.org/TR/2010/REC-xml-stylesheet-20101028/

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Media feature pack windows 10 ошибка 0x80004005
  • Media encoder код ошибки 1610153423