@media
Содержание:
- Что такое медиа-запрос?
- CSS Tutorial
- CSS Media Queries — More Examples
- CSS Advanced
- More Examples
- Media Queries For Menus
- Media Queries For Menus
- CSS Properties
- Another Breakpoint
- Media Queries For Columns
- CSS Syntax
- Min Width to Max Width
- CSS Advanced
- Min Width to Max Width
- CSS Advanced
- Definition and Usage
- Typical Device Breakpoints
- CSS Media Queries — More Examples
- CSS Tutorial
- Media Queries For Columns
Что такое медиа-запрос?
Медиа-запрос — это способ контролировать представление контента. Он состоит из типа и минимум одного выражения, которое проверяет выполнение условий для указанных характеристик устройства.
Как уже было сказано, в настоящее время широко реализована поддержка двух типов: «screen» и «print«.
При наличии условных выражений контент может выводиться по-разному для различных типов устройств, без ущерба для содержимого.
Как определить медиа-запрос?
Простой медиа-запрос может быть определен в HTML следующим образом:
<link rel="stylesheet" media="print" href="myexample.css" />
В приведенном выше примере, мы указали, что для типа медиа «print» браузер пользователя должен использовать таблицу стилей myexample.css.
То же самое может быть объявлено как @import-правило в CSS:
@import url(myexample.css) print;
Когда браузер пользователя обрабатывает приведенный выше медиа-запрос, он определяет, текущий тип медиа — print или нет. Если да, то будет применяться таблица стилей «myexample.css«. Следовательно, вывод медиа-запросов можно организовать в зависимости от выполняемых условий.
Если тип устройств не задан или задано значение ‘all‘, то стили будут применяться для всех типов медиа.
Например:
<link rel="stylesheet" href="myexample.css" /> <link rel="stylesheet" media="all" href="myexample.css" />
В приведенном выше примере, стили будет применяться как для типа ‘print‘, так и для типа ‘screen‘. Это эквивалентные объявления. Как и следующий CSS-код:
@media all { … } @media { … }
Медиа-запросы могут быть объединены в сложные медиа-запросы:
<link rel="stylesheet" media="print, projection" href="myexample.css" />
Этот запрос также может быть объявлен следующим образом:
@media print, projection { … }
Медиа-запросы также поддерживают логическое выражение NOT, используя ключевое слово «NOT«:
<link rel="stylesheet" media="not print, screen" href="myexample.css" />
В приведенном выше примере мы указали, что стили не будут применяться к типу ‘print‘, а только к типу ‘screen‘.
Характеристики устройств, которые можно указать в медиа-запросах
- color;
- color-index;
- device-aspect-ratio;
- device-height;
- device-width;
- grid;
- height;
- monochrome;
- resolution;
- scan;
- width.
Завершение
Из этой статьи вы узнали о медиа-запросах CSS3. Я надеюсь, что вы нашли эту информацию полезной для себя.
Данная публикация является переводом статьи «Understanding CSS3 Media Queries» , подготовленная редакцией проекта.
CSS Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !important
CSS Media Queries — More Examples
Let us look at some more examples of using media queries.
Media queries are a popular technique for delivering a tailored style sheet to different devices. To demonstrate a simple example, we can change the background color for different devices:
Example
/* Set the background color of body to tan */body {
background-color: tan;}/* On
screens that are 992px or less, set the background color to blue */@media
screen and (max-width: 992px) { body {
background-color: blue; }}/* On screens that are 600px or less,
set the
background color to olive */@media screen and (max-width: 600px) {
body { background-color: olive; }}
Do you wonder why we use exactly 992px and 600px? They are what we call «typical breakpoints» for devices. You can read more about typical breakpoints in our Responsive Web Design Tutorial.
CSS Advanced
CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
CSS Shadows
Shadow Effects
Box Shadow
CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries
CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive
More Examples
Example
Hide an element when the browser’s width is 600px wide or less:
@media screen and (max-width: 600px) { div.example { display:
none;
}}
Example
Use mediaqueries to set the background-color to lavender if the viewport is
800 pixels wide or wider, to lightgreen if the viewport is between 400 and 799 pixels wide.
If the viewport is smaller than 400 pixels, the background-color is lightblue:
body { background-color: lightblue;}@media screen and (min-width:
400px) { body {
background-color: lightgreen; }}@media
screen and (min-width: 800px) { body {
background-color: lavender; }}
Example
Create a responsive navigation menu (displayed horizontally on large screens and vertically on small screens):
@media screen and (max-width: 600px) { .topnav a {
float: none; width: 100%;
}}
Example
Use media queries to create a responsive column layout:
/* On screens that are 992px wide or less, go from four columns to two
columns */@media screen and (max-width: 992px) { .column {
width: 50%; }}/* On screens that are 600px wide or less, make the columns stack
on top of each other instead of next to each other */@media screen and (max-width:
600px) { .column { width: 100%;
}}
Example
Use media queries to create a responsive website:
Example
Media queries can also be used to change layout of a page depending on the
orientation of the browser. You can have a set of CSS properties that will only
apply when the browser window is wider than its height, a so called «Landscape»
orientation.
Use a lightblue background color if the orientation is in landscape mode:
@media only screen and (orientation:
landscape) { body {
background-color: lightblue; }}
Example
Use mediaqueries to set the text color to green when the document is
displayed on the screen, and to black when it is printed:
@media screen { body {
color: green; }}@media print { body { color: black;
}}
Example
Comma separated list: add an additional media query to an already existing one, using a comma (this will behave like an OR operator):
/* When the width is between 600px and 900px OR above 1100px — change the
appearance of <div> */@media screen and (max-width: 900px) and
(min-width: 600px), (min-width: 1100px) { div.example {
font-size: 50px; padding: 50px;
border: 8px solid black; background: yellow;
}}
Media Queries For Menus
In this example, we use media queries to create a responsive navigation menu, that varies
in design on different screen sizes.
Large screens:
Home
Link 1
Link 2
Link 3
Small screens:
Home
Link 1
Link 2
Link 3
Example
/* The navbar container */.topnav { overflow: hidden;
background-color: #333;}/* Navbar links */.topnav a { float:
left; display: block; color:
white; text-align: center; padding: 14px 16px;
text-decoration: none;}
/* On screens that are 600px wide or less, make the menu links stack on top
of each other instead of next to each other */@media screen and (max-width: 600px) {
.topnav a { float: none; width:
100%; }}
Media Queries For Menus
In this example, we use media queries to create a responsive navigation menu, that varies
in design on different screen sizes.
Large screens:
Home
Link 1
Link 2
Link 3
Small screens:
Home
Link 1
Link 2
Link 3
Example
/* The navbar container */.topnav { overflow: hidden;
background-color: #333;}/* Navbar links */.topnav a { float:
left; display: block; color:
white; text-align: center; padding: 14px 16px;
text-decoration: none;}
/* On screens that are 600px wide or less, make the menu links stack on top
of each other instead of next to each other */@media screen and (max-width: 600px) {
.topnav a { float: none; width:
100%; }}
CSS Properties
align-contentalign-itemsalign-selfallanimationanimation-delayanimation-directionanimation-durationanimation-fill-modeanimation-iteration-countanimation-nameanimation-play-stateanimation-timing-functionbackface-visibilitybackgroundbackground-attachmentbackground-blend-modebackground-clipbackground-colorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizeborderborder-bottomborder-bottom-colorborder-bottom-left-radiusborder-bottom-right-radiusborder-bottom-styleborder-bottom-widthborder-collapseborder-colorborder-imageborder-image-outsetborder-image-repeatborder-image-sliceborder-image-sourceborder-image-widthborder-leftborder-left-colorborder-left-styleborder-left-widthborder-radiusborder-rightborder-right-colorborder-right-styleborder-right-widthborder-spacingborder-styleborder-topborder-top-colorborder-top-left-radiusborder-top-right-radiusborder-top-styleborder-top-widthborder-widthbottombox-decoration-breakbox-shadowbox-sizingbreak-afterbreak-beforebreak-insidecaption-sidecaret-color@charsetclearclipclip-pathcolorcolumn-countcolumn-fillcolumn-gapcolumn-rulecolumn-rule-colorcolumn-rule-stylecolumn-rule-widthcolumn-spancolumn-widthcolumnscontentcounter-incrementcounter-resetcursordirectiondisplayempty-cellsfilterflexflex-basisflex-directionflex-flowflex-growflex-shrinkflex-wrapfloatfont@font-facefont-familyfont-feature-settingsfont-kerningfont-sizefont-size-adjustfont-stretchfont-stylefont-variantfont-variant-capsfont-weightgapgridgrid-areagrid-auto-columnsgrid-auto-flowgrid-auto-rowsgrid-columngrid-column-endgrid-column-gapgrid-column-startgrid-gapgrid-rowgrid-row-endgrid-row-gapgrid-row-startgrid-templategrid-template-areasgrid-template-columnsgrid-template-rowshanging-punctuationheighthyphens@importisolationjustify-content@keyframesleftletter-spacingline-heightlist-stylelist-style-imagelist-style-positionlist-style-typemarginmargin-bottommargin-leftmargin-rightmargin-topmax-heightmax-width@mediamin-heightmin-widthmix-blend-modeobject-fitobject-positionopacityorderoutlineoutline-coloroutline-offsetoutline-styleoutline-widthoverflowoverflow-xoverflow-ypaddingpadding-bottompadding-leftpadding-rightpadding-toppage-break-afterpage-break-beforepage-break-insideperspectiveperspective-originpointer-eventspositionquotesresizerightrow-gapscroll-behaviortab-sizetable-layouttext-aligntext-align-lasttext-decorationtext-decoration-colortext-decoration-linetext-decoration-styletext-indenttext-justifytext-overflowtext-shadowtext-transformtoptransformtransform-origintransform-styletransitiontransition-delaytransition-durationtransition-propertytransition-timing-functionunicode-bidiuser-selectvertical-alignvisibilitywhite-spacewidthword-breakword-spacingword-wrapwriting-modez-index
Another Breakpoint
You can add as many breakpoints as you like.
We will also insert a breakpoint between tablets and mobile phones.
Desktop
Tablet
Phone
We do this by adding one more media query (at 600px), and a set of new classes for devices larger than 600px
(but smaller than 768px):
Example
Note that the two sets of classes are almost identical, the only
difference is the name ( and ):
/* For mobile phones: */ { width: 100%;}@media only screen and (min-width: 600px) {
/* For tablets: */ .col-s-1 {width: 8.33%;} .col-s-2 {width: 16.66%;}
.col-s-3 {width: 25%;} .col-s-4 {width: 33.33%;} .col-s-5 {width: 41.66%;}
.col-s-6 {width: 50%;} .col-s-7 {width: 58.33%;} .col-s-8 {width: 66.66%;}
.col-s-9 {width: 75%;} .col-s-10 {width: 83.33%;} .col-s-11 {width: 91.66%;}
.col-s-12 {width: 100%;}}@media only screen and (min-width:
768px) { /* For desktop: */ .col-1 {width: 8.33%;} .col-2 {width: 16.66%;}
.col-3 {width: 25%;} .col-4 {width: 33.33%;} .col-5 {width: 41.66%;}
.col-6 {width: 50%;} .col-7 {width: 58.33%;} .col-8 {width: 66.66%;}
.col-9 {width: 75%;} .col-10 {width: 83.33%;} .col-11 {width: 91.66%;}
.col-12 {width: 100%;}}
It might seem odd that we have two sets of identical classes, but it gives us the
opportunity in HTML, to decide what will happen with the columns at each
breakpoint:
HTML Example
For desktop:
The first and the third section will both span 3 columns each. The middle section will span 6 columns.
For tablets:
The first section will span 3 columns, the second will span 9, and the third section will be displayed below the first two sections, and it will span 12 columns:
<div class=»row»> <div class=»col-3 col-s-3″>…</div> <div
class=»col-6 col-s-9″>…</div> <div
class=»col-3 col-s-12″>…</div></div>
Media Queries For Columns
A common use of media queries, is to create a flexible layout. In this example, we create a layout that varies between four, two and full-width columns, depending on different screen sizes:
Large screens:
Medium screens:
Small screens:
Example
/* Create four equal columns that floats next to each other */.column {
float: left; width: 25%;}/* On screens that are 992px
wide or less, go from
four columns to two columns */@media screen and (max-width: 992px) {
.column { width: 50%; }}/* On screens that are
600px wide or less, make
the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) { .column { width:
100%; }}
Tip: A more modern way of creating column layouts, is to use CSS Flexbox (see example below).
However, it is not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use floats (as shown above).
To learn more about the Flexible Box Layout Module, read our CSS Flexbox chapter.
To learn more about Responsive Web Design, read our Responsive Web Design Tutorial.
Example
/* Container for flexboxes */.row { display: flex;
flex-wrap: wrap;}/* Create four equal columns */.column { flex: 25%;
padding: 20px;}/* On screens that are 992px wide or less, go from
four columns to two columns */@media screen and (max-width: 992px) {
.column { flex: 50%; }}/* On screens that are 600px wide or less, make
the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) { .row {
flex-direction: column; }}
CSS Syntax
@media not|only mediatype and (mediafeature and|or|not
mediafeature) { CSS-Code;}
meaning of the not, only and and keywords:
not: The not keyword inverts the meaning of an entire media
query.
only: The only keyword prevents older browsers that do not support media queries with media features from applying the specified styles.
It has no effect on modern browsers.
and: The and keyword combines a media feature with a media
type or other media features.
They are all optional. However, if you use not or
only, you must also specify a media type.
You can also have different stylesheets for different media, like
this:
<link rel=»stylesheet» media=»screen and (min-width:
900px)» href=»widescreen.css»><link rel=»stylesheet» media=»screen and (max-width:
600px)» href=»smallscreen.css»>….
Min Width to Max Width
You can also use the values to set a minimum width and a maximum width.
For example, when the browser’s width is between 600 and 900px, change the
appearance of a <div> element:
Example
@media screen and (max-width: 900px) and (min-width: 600px) { div.example {
font-size: 50px; padding: 50px;
border: 8px solid black; background: yellow; }}
Using an additional value: In the example below, we add an additional media query to our already
existing one using a comma (this will behave like an OR operator):
Example
/* When the width is between 600px and 900px OR above 1100px
— change the appearance of <div> */@media screen and (max-width: 900px) and (min-width:
600px), (min-width:
1100px) { div.example {
font-size: 50px; padding: 50px;
border: 8px solid black; background: yellow; }}
CSS Advanced
CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
CSS Shadows
Shadow Effects
Box Shadow
CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries
CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive
Min Width to Max Width
You can also use the values to set a minimum width and a maximum width.
For example, when the browser’s width is between 600 and 900px, change the
appearance of a <div> element:
Example
@media screen and (max-width: 900px) and (min-width: 600px) { div.example {
font-size: 50px; padding: 50px;
border: 8px solid black; background: yellow; }}
Using an additional value: In the example below, we add an additional media query to our already
existing one using a comma (this will behave like an OR operator):
Example
/* When the width is between 600px and 900px OR above 1100px
— change the appearance of <div> */@media screen and (max-width: 900px) and (min-width:
600px), (min-width:
1100px) { div.example {
font-size: 50px; padding: 50px;
border: 8px solid black; background: yellow; }}
CSS Advanced
CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients
CSS Shadows
Shadow Effects
Box Shadow
CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries
CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive
Definition and Usage
The rule is used in media queries to apply different styles for different media types/devices.
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 (responsive web design) to desktops, laptops, tablets, and mobile phones.
You can also use media queries to specify that certain styles are only for printed documents or for screen readers (mediatype: print, screen, or speech).
In addition to media types, there are also media features. Media features
provide more specific details to media queries, by allowing to test for a
specific feature of the user agent or display device. For example, you
can apply styles to only those screens that are greater, or smaller, than a
certain width.
Typical Device Breakpoints
There are tons of screens and devices with different heights and widths, so it is hard to create an exact breakpoint for each device. To keep things simple you could target
five groups:
Example
/*
Extra small devices (phones, 600px and down) */@media only screen and (max-width: 600px)
{…} /* Small devices (portrait tablets and large phones, 600px and up)
*/@media only screen and (min-width: 600px) {…} /* Medium devices (landscape tablets, 768px and up) */
@media only screen and (min-width: 768px) {…} /* Large devices (laptops/desktops, 992px and up)
*/
@media only screen and (min-width: 992px) {…} /* Extra large devices (large
laptops and desktops,
1200px and up) */@media only screen and (min-width: 1200px) {…}
CSS Media Queries — More Examples
Let us look at some more examples of using media queries.
Media queries are a popular technique for delivering a tailored style sheet to different devices. To demonstrate a simple example, we can change the background color for different devices:
Example
/* Set the background color of body to tan */body {
background-color: tan;}/* On
screens that are 992px or less, set the background color to blue */@media
screen and (max-width: 992px) { body {
background-color: blue; }}/* On screens that are 600px or less,
set the
background color to olive */@media screen and (max-width: 600px) {
body { background-color: olive; }}
Do you wonder why we use exactly 992px and 600px? They are what we call «typical breakpoints» for devices. You can read more about typical breakpoints in our Responsive Web Design Tutorial.
CSS Tutorial
CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL
CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand
CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders
CSS Margins
Margins
Margin Collapse
CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset
CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow
CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand
CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive
CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples
CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar
CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !important
Media Queries For Columns
A common use of media queries, is to create a flexible layout. In this example, we create a layout that varies between four, two and full-width columns, depending on different screen sizes:
Large screens:
Medium screens:
Small screens:
Example
/* Create four equal columns that floats next to each other */.column {
float: left; width: 25%;}/* On screens that are 992px
wide or less, go from
four columns to two columns */@media screen and (max-width: 992px) {
.column { width: 50%; }}/* On screens that are
600px wide or less, make
the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) { .column { width:
100%; }}
Tip: A more modern way of creating column layouts, is to use CSS Flexbox (see example below).
However, it is not supported in Internet Explorer 10 and earlier versions. If you require IE6-10 support, use floats (as shown above).
To learn more about the Flexible Box Layout Module, read our CSS Flexbox chapter.
To learn more about Responsive Web Design, read our Responsive Web Design Tutorial.
Example
/* Container for flexboxes */.row { display: flex;
flex-wrap: wrap;}/* Create four equal columns */.column { flex: 25%;
padding: 20px;}/* On screens that are 992px wide or less, go from
four columns to two columns */@media screen and (max-width: 992px) {
.column { flex: 50%; }}/* On screens that are 600px wide or less, make
the columns stack on top of each other instead of next to each other */
@media screen and (max-width: 600px) { .row {
flex-direction: column; }}