@media

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;  }}

Media Features

Value Description
any-hover Does any available input mechanism allow the user to hover over
elements? (added in Media Queries Level 4)
any-pointer Is any available input mechanism a pointing device, and if so, how
accurate is it? (added in Media Queries Level 4)
aspect-ratio The ratio between the width and the height of the viewport
color The number of bits per color component for the output device
color-gamut The approximate range of colors that are supported by the user agent and
output device (added in Media Queries Level 4)
color-index The number of colors the device can display
grid Whether the device is a grid or bitmap
height The viewport height
hover Does the primary input mechanism allow the user to hover over elements?
(added in Media Queries Level 4)
inverted-colors Is the browser or underlying OS inverting colors? (added in Media
Queries Level 4)
light-level Current ambient light level (added in Media Queries Level 4)
max-aspect-ratio The maximum ratio between the width and the height of the display area
max-color The maximum number of bits per color component for the output device
max-color-index The maximum number of colors the device can display
max-height The maximum height of the display area, such as a browser window
max-monochrome The maximum number of bits per «color» on a monochrome (greyscale) device
max-resolution The maximum resolution of the device, using dpi or dpcm
max-width The maximum width of the display area, such as a browser window
min-aspect-ratio The minimum ratio between the width and the height of the display area
min-color The minimum number of bits per color component for the output device
min-color-index The minimum number of colors the device can display
min-height The minimum height of the display area, such as a browser window
min-monochrome The minimum number of bits per «color» on a monochrome (greyscale) device
min-resolution The minimum resolution of the device, using dpi or dpcm
min-width The minimum width of the display area, such as a browser window
monochrome The number of bits per «color» on a monochrome (greyscale) device
orientation The orientation of the viewport (landscape or portrait mode)
overflow-block How does the output device handle content that overflows the viewport along the block axis (added in Media Queries Level 4)
overflow-inline Can content that overflows the viewport along the inline axis be scrolled (added in Media Queries Level 4)
pointer Is the primary input mechanism a pointing device, and if so, how
accurate is it? (added in Media Queries Level 4)
resolution The resolution of the output device, using dpi or dpcm
scan The scanning process of the output device
scripting Is scripting (e.g. JavaScript) available? (added in Media Queries Level
4)
update How quickly can the output device modify the appearance of the content (added in Media Queries Level 4)
width The viewport width

Поддержка веб-браузерами

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

  • Хорошая новость состоит в том, что большинство современных браузеров (включая браузеры для смартфонов) поддерживает CSS-медиазапросы.
  • Плохая новость состоит в том, что в Microsoft Windows Internet Explorer версии 8 поддержка медиазапросов все еще отсутствует.

С точки зрения большинства профессиональных веб-разработчиков это означает, что для поддержки медиазапросов в Internet Explorer м необходимо специальное решение. Ниже описывается одно из таких решений под названием respond.js, которое представляет собой т.н. polyfill-скрипт на базе JavaScript.

Реализация polyfill-скрипта с помощью respond.js

Respond.js — это небольшая JavaScript-библиотека, которая расширяет возможности веб-браузеров и поддерживает CSS-медиазапросы в тех браузерах, где отсутствует их нативная поддержка. Polyfill-скрипт циклически проходит по всему CSS-коду, на который ссылается данная страница, и анализирует CSS-правила, использующие медиазапросы. Затем этот скрипт отслеживает изменения ширины в браузере, добавляя и удаляя стили в соответствии с CSS-медиазапросом. Тем самым обеспечивается работа CSS-медиазапросов в браузерах, не имеющих их встроенной поддержки.

Это решение базируется на JavaScript, поэтому для работы polyfill-скрипта в браузере должна быть активирована технология JavaScript. Этот скрипт предназначен лишь для поддержки медиазапросов, в которых фигурируют минимальные или максимальные значения , что требуется для создания динамичных дизайнов. Он не обеспечивает полномасштабной замены всех возможных CSS-медиазапросов. За дополнительной информацией о функциях и ограничениях этого скрипта обратитесь к разделу .

Respond.js — это один из множества доступных polyfill-скриптов с открытым исходным кодом для поддержки медиазапросов. Если respond.js не удовлетворяет ваши потребности, будет несложно найти альтернативные варианты.

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 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 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 object-fitCSS 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;  }}

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 Query Syntax

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

@media not|only mediatype and (expressions) {  CSS-Code;}

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
type will be implied.

You can also have different stylesheets for different media:

<link rel=»stylesheet» media=»mediatype and|not|only (expressions)»
href=»print.css»>

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) {…}

Динамичный дизайн

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

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

Медиазапросы позволяют разработчику написать CSS-код, который будет автоматически менять дизайн для оптимизации пользовательского интерфейса на экранах различных размеров.

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 Style
Font Size
Font Google
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 Specificity

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

@media screen and (min-width: 480px) {  body {
    background-color: lightgreen;  }}

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

@media screen and (min-width: 480px) {  #leftsidebar
{width: 200px; float: left;}  #main
{margin-left: 216px;}}

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.

❮ Previous
Next ❯

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 reverts 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»>….

Организация медиазапросов

Теперь, когда вы знаете, как писать медиазапросы, пришло время подумать об их развертывании в базе вашего CSS-кода — логичным и организованным образом. Принятие решения о том, как организовать медиазапросы, в значительной степени является вопросом личных предпочтений. В данном разделе рассматриваются преимущества и недостатки двух основных подходов.

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

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

Ни один из подходов нельзя однозначно назвать предпочтительным. Выбирайте тот подход, который больше подходит для вашего проекта и для вашей рабочей группы.

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 Style
Font Size
Font Google
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 Specificity

Полезные медиафункции

Имеется несколько медиафункций, в том числе width, color и grid, которые можно использовать в медиазапросах. В данной статье не описываются все возможные медиафункции. Полный список этих функций содержится в документации организации World Wide Web Consortium (W3C) по медиазапросам (см. раздел ).

Для проектирования динамичных веб-сайтов достаточно знать лишь несколько медиафункций: orientation (ориентация), width (ширина) и height (высота). Orientation – это простая медиафункция, которая может иметь значение или
. Эти значения соответствуют положению телефона или планшета в руке пользователя, что позволяет разработчику оптимизировать контент для обоих вышеуказанных формфакторов. Считается, что экран находится в портретном режиме, если высота превышает длину, и в альбомном режиме, если ширина больше высоты. В листинге 8 показан пример использования функции .

Листинг 8. Медиазапрос с функцией
@media (orientation:portrait) { ... }

Функции height и width ведут себя аналогично; обе допускают использование префиксов
и . В листинге 9 показан правильно построенный медиазапрос с использованием этих функций.

Листинг 9. Медиазапрос с функциями height и width
@media (min-width:800px) and (min-height:400px) { ... }

Медиафункции и
можно использовать без префикса или
(см. листинг 10).

Листинг 10. Медиафункции без префиксов и
@media (width:800px) and (height:400px) { ... }

Медиазапрос в листинге 10 соответствует ситуации, когда экран имеет ширину ровно 800 пикселей и высоту ровно 400 пикселей. В реальном мире этот медиазапрос, вероятно, окажется слишком конкретным, чтобы быть полезным. По всей вероятности, подавляющее большинство посетителей веб-сайтов никогда не встретятся со сценарием, ориентированным на точные размеры экрана. Как правило, в динамичном дизайне при определении параметров экрана указываются диапазоны размеров.

Теперь — в качестве естественного продолжения медиазапроса с диапазоном размеров — рассмотрим несколько распространенных медиазапросов, которые могут оказаться небесполезными при проектировании динамичного сайта.

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>

Add a Breakpoint

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

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

Desktop

Phone

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

Example

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

/* 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%;}@media only screen and (max-width: 768px) {  /* For mobile phones: */
 
{    width: 100%;  }}

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.

Другой Breakpoint

Вы можете добавить столько точек останова, как вам нравится.

Мы также вставить контрольную точку между таблетками и мобильными телефонами.

рабочий стол

таблетка

Телефон

Мы делаем это, добавив еще один медиа-запрос (на 600px), а также набор новых классов для устройств размером более 600 пикселей (но меньше, чем 768px):

пример

Обратите внимание , что два набора классов почти идентичны, единственное отличие это имя ( col- и col-m- ):

/* For mobile phones: */ {    width: 100%;}@media only screen and (min-width: 600px) {   
/* For tablets: */    .col-m-1 {width: 8.33%;}    .col-m-2 {width: 16.66%;}    .col-m-3 {width: 25%;}    .col-m-4 {width: 33.33%;}    .col-m-5 {width: 41.66%;}    .col-m-6 {width: 50%;}    .col-m-7 {width: 58.33%;}    .col-m-8 {width: 66.66%;}    .col-m-9 {width: 75%;}    .col-m-10 {width: 83.33%;}    .col-m-11 {width: 91.66%;}    .col-m-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%;}}

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

HTML Пример

Для рабочего стола:

Первая и третья секция будет охватывать как 3 колонки каждый. Средняя секция будет охватывать 6 столбцов.

Для таблеток:

Первый раздел будет охватывать 3 колонки, второй будет охватывать 9, а третья секция будет отображаться ниже первых двух секций, и он будет охватывать 12 столбцов:

<div class=»row»><div class=»col-3 col-m-3″>…</div><div
class=»col-6 col-m-9″>…</div><div
class=»col-3 col-m-12″>…</div></div>

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS 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 object-fitCSS 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

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 Style
Font Size
Font Google
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 Specificity

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 Style
Font Size
Font Google
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 Specificity

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS 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 object-fitCSS 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

Медиазапросы в SASS

Поддержка технологии SASS (Syntactically Awesome Style Sheets) встроена в инфраструктуру Ruby on Rails, что способствует популярности SASS и ее все более широкому распространению в сообществе веб-разработчиков. Детальное рассмотрение SASS выходит за рамки данной статьи, я лишь изложу основы использования медиазапросов в таблицах стилей на базе SASS. Для получения дополнительной информации о SASS обратитесь к разделу .

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

Листинг 11. Вложенный медиазапрос
#header {
  width: 400px;
  @media (min-width: 800px) {
    width: 100%;
  }
}

В результате компиляции примера в листинге 11 получится код, показанный в листинге 12.

Always Design for Mobile First

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

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

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

Example

/* For mobile phones: */ {  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%;}}

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS 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 object-fitCSS 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

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

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