Conclusion
Nowadays it is necessary for your website to be responsive. And if you want to make responsive websites then media query is at the core. For responsive websites, the most famous choice is bootstrap framework, even bootstrap use media query at its code for responsiveness.
Points to remember:
- Media query can conditionally apply CSS properties to certain elements of the webpage when the device type of viewport dimension matches.
It can load different resources only for a targeted device or targeted screen size. like in the <picture> element you can set multiple sources of an image that will load when a certain media condition satisfies.
It will load an file that is attached for a media query even when the query is false in <link> element but will not apply its property to the page until the condition is true.
Using media query can also be used in JavaScript.
❮ PrevHome ❯
Using Media Queries to create a stylesheet for phones
To get started we can take a look at a very simple example. The below layout is a very simple two column layout.
A very simple two column layout
To make it easier to read on a phone I have decided to linearize the entire design making it all one column, and also to make the header area much smaller so readers don’t need to scroll past the header before getting to any content.
The first way to use media queries is to have the alternate section of CSS right inside your single stylesheet. So to target small devices we can use the following syntax:
We can then add our alternate CSS for small screen and width devices inside the curly braces. By using the cascade we can simply overwrite any styles rules we set for desktop browsers earlier in our CSS. As long as this section comes last in your CSS it will overwrite the previous rules. So, to linearize our layout and use a smaller header graphic I can add the following:
In the code above I am using an alternate background image and reducing the height of the header, then setting the content and navigation to float none and overwriting the width set earlier in the stylesheet. These rules only come into play on a small screen device.
My simple example as displayed on an iPhone
Conclusion
Responsive Design is the practice of making sure your content looks good on all screen sizes. Everything in the website including layouts, fonts and images should automatically adapt to the user’s device.
In CSS, a media query is used to apply a set of styles based on the browser’s characteristics including width, height, or screen resolution.
Here is the basic syntax for a media query in CSS.
The media type is optional unless you are using the or logical operators. If the media type is omitted then the media query will target all devices.
I hope you found this article helpful and best of luck on your CSS journey.
How to use CSS media queries: the syntax
Before I get to the different media features themselves, let’s cover the basic syntax for a CSS media query. A media query looks like this:
To help you break down each of the parts, here’s a handy image that identifies all the parts of a typical CSS media query:
And here’s a summary along with further details on what’s in the image:
- – The CSS at-rule that indicates that you’re writing a media query
- – One of the available media types to identify which devices should the media query should target. This is optional if you’re not using the and operators.
- – A media query modifier, also called a logical operator, that helps you conditionally target certain devices and media features.
- – One of numerous media features and values available to target specific device sizes, device types, device capabilities, etc.
- – The selectors and CSS rules, nested inside opening and closing curly braces, indicating what CSS rules you want to apply to your media queries.
You can include as much CSS as you want inside the opening and closing media query curly braces, as long as the CSS is correctly formatted, so it doesn’t break (i.e., no missing curly braces for any selectors, etc).
How to use #CSS media queries: a complete #guide for beginners ️
Media query examples
Let’s take a look at a few examples that show how to use media queries in CSS.
In this first example, we want the background color to change to blue when the width of the device is 600px or less.
In the CSS, we want to add a for the media query which tells the computer to target devices with a screen width of 600px and less.
Inside the media query, we change the background styles for the body to .
Here is the complete media query:
Here is the CodePen example. If you click on the Edit on CodePen in the top right hand corner, you can test this out on Codepen.
In this second example, we want to change the background color from blue to red if the device has a width between 600 and 768px. We can use the operator to accomplish this.
Here is the complete CodePen example for you to try out:
When you test it out, you should see that the background color is blue if the width of the screen is below 600px or above 768px.
CSS Media Queries in Action
Popular travel website Airbnb showcases the benefits of media queries. So let’s delve deeper into how Airbnb leverages CSS media queries to deliver a visually stunning and responsive website.
Desktop Media Query
The desktop version of the Airbnb website showcases beautiful images and effortless navigation in a sophisticated multi-column layout. The prominently positioned navigation menu and easy-to-use search bar let users quickly filter their preferences.
As the screen size decreases, the website adapts to a single-column layout. Images get smaller but remain high quality. The navigation menu becomes more concise, remaining user-friendly.
Tablet Media Query
The Airbnb website optimizes its layout for touch interaction on tablet devices. The navigation menu takes up less screen space while still maintaining easy accessibility. The search bar also moves to the top of the page.
The listing images are scaled down to fit the smaller screen size, while still maintaining their quality, providing users with a visually stunning experience.
Mobile Media Query
Airbnb’s mobile website design prioritizes user experience and accessibility. The navigation menu is simplified to a hamburger icon. The search bar is front and center for quick filtering of results.
High-quality images are scaled down but easily browsable through swipeable galleries. The vertical scrolling layout provides seamless exploration with just one hand. The result is a user-friendly, enjoyable browsing experience on the go.
The History of Media Queries
CSS media queries were introduced in 1998 but gained popularity in the early 2010s with the rise of mobile devices. Ethan Marcotte’s 2010 article, “Responsive Web Design,” was a game-changer. It proposed the use of media queries to build flexible, adaptive layouts that can adjust to different screen sizes and devices.
CSS3’s 2011 release brought significant improvements to media queries. This update introduced new features such as min-width, max-width, device-width, aspect-ratio, and pointer.
Today, media queries are essential to web design. They provide providing designers with unparalleled control over their website’s appearance and usability.
Sites can now have dynamic layouts that can adjust to the ever-changing digital landscape. By targeting specific devices, media queries have made websites more accessible.
Wrapping It Up!
Media queries in CSS are a helpful friend in building up a responsive design and developing with more control and enhancement capabilities. Media queries in CSS although started rough, are used exhaustively today in projects and web applications. You can follow this CSS cheat sheet to brush up on your responsive CSS skills.
This post highlighted the main goals of media queries in CSS and how to achieve responsiveness with them using different rules and expressions. It amazes me to see such beautiful designs on Codepen and other websites that developers build with minimum library support.
Coming to the end of the post, we call for such designs in the comment sections and would love to include the best of them in this post. Hope to see some creative work!
What is CSS media queries?
CSS media queries are useful for modifying websites and apps based on the device type or a specific characteristic, such as the screen size or viewport width.
Can you use media queries in CSS?
Even though media queries are typically associated with CSS, they can also be used in HTML and JavaScript. Also, you can use media queries in HTML directly.
What is the responsive in CSS?
A responsive web design means your site will look great on any device: desktop, tablet, or phone. A responsive design is achieved by using CSS and HTML to resize, hide, shrink, enlarge, or move the content to make it look good on any screen.
How do I make my CSS code responsive?
The viewport meta tag must be included in the HTML code to make a web page responsive. This sets the page width to the device width and the initial zoom to 1. If the meta tag is not included, mobile or tablet users will see a desktop version of your website that might not fit properly on their screens.
What is responsive coding?
Responsive coding refers to designing and developing websites or applications that can adapt and adjust their layout and content to different screen sizes and devices. A responsive website can be viewed and used effectively on desktops, laptops, tablets, and smartphones without losing functionality or usability.
What is a media query CSS?
Media queries allow you to apply different CSS styles depending on the type of device being used or other characteristics such as screen resolution or browser viewport width. They are used for the following: To conditionally apply styles with @media or @import rules.
How to use a media query in CSS?
Media queries in CSS allow you to apply different styles to a webpage based on the characteristics of the device or screen size. To use a media query in CSS, you can follow these steps:
- Define the media query using the @media rule followed by the media type and the condition to apply the styles.
- Within the curly braces of the media query, write the CSS styles that you want to apply to the targeted screens.
You can also use other media types such as print or speech, and other conditions such as minimum width or height, device orientation, etc., to target specific devices or scenarios.
How to write media queries in CSS?
Write a media query in CSS by using the @media rule and specifying the conditions, such as screen size, orientation, or device type, within parentheses. Inside the curly braces, define the CSS styles to be applied under those conditions.
How to use media query in inline CSS?
Using media queries in inline CSS is not recommended. It is best to separate the CSS code into an external stylesheet or include it within the tags in the section of an HTML document. This promotes better organization, maintainability, and reusability of CSS styles.
How to apply media query in CSS?
Apply a media query in CSS by wrapping the desired CSS styles within an @media rule, specifying the desired conditions within parentheses. These conditions can target specific screen sizes, orientations, or device types, allowing for responsive design and layout adjustments.
How to add a media query in CCS?
To add a media query in CSS, use the rule followed by the desired conditions within parentheses, and enclose the CSS styles inside curly braces. Example:
Option 1: Monitor the Viewport Dimensions
This was the only option in the dark days before media queries were implemented. JavaScript would listen for browser “resize” events, analyse the viewport dimensions using and (or and in old IEs), and react accordingly.
This code outputs the calculated small, medium, or large string to the console:
You can view a working demonstration here. (If using a desktop browser, open this link in a new window to make resizing easier. Mobile users can rotate the device.)
The above example examines the viewport size as the browser is resized; determines whether it’s small, medium, or large; and sets that as a class on the body element, which changes the background color.
The advantages of this method include:
- It works in every browser that can run JavaScript — even ancient applications.
- You’re capturing the exact dimensions and can react accordingly.
The disadvantages:
- It’s an old technique that requires considerable code.
- Is it too exact? Do you really need to know when the width is 966px versus 967px?
- You may need to manually match dimensions to a corresponding CSS media query.
- Users can resize the browser rapidly, causing the handler function to run again each time. This can overload older and slower browsers by throttling the event. It can only be triggered once every 500 milliseconds.
In summary, do not monitor viewport dimensions unless you have very specific and complex sizing requirements.
Синтаксис медиа-запросов
Запись медиа-запросов в теле сайта выглядит вот так:
Курс Fullstack Web Development.
Володій навичками розробки як на фронтенді, так і на бекенді. За такими фахівцями черга в компаніях!
Отримати інформацію про курс
Можно добавлять их в HTML-части сайта, внутри таблицы CSS, а также напрямую в код страницы. Если речь идет о старых браузерах, то можно подключить специальную JavaScript-библиотеку, чтобы медиа-запросы функционировали корректно.
Главные виды устройств, которые можно прописывать в медиа-запросах:
- все устройства — ;
- устройства с экранами — ;
- синтезаторы речи — ;
- принтеры или страница предварительного просмотра для печати — .
Когда-то раньше также использовались:
- проекторы — ;Курс Frontend.
На курсі ти освоїш стильний дизайн. Стань майстром програмування зовнішнього вигляду сайтів та розкрий свій талант у світі веб-розробки.
Більше про курс
телевизоры — ;
смартфоны и другие мобильные устройства — .
Но в современной версии media queries 4 их принято считать устаревшими.
Также медиа-запросы могут содержать в себе логические операторы, такие как:
- — все условия должны выполняться одновременно;
- — хотя бы одно из условия должно выполняться, аналогично «или»;
- — отрицание условия (имеет более низкий приоритет, чем , а значит будет выполняться после него).
Для составления условий можно использовать некоторые функции:
- ( и ) — определяет требования к ширине браузера, наибольшее и наименьшее значения этого параметра в пикселях или других единицах: ;
- , и — прописывает требования к высоте браузера, аналогично функциям ширины: ;Курс QA.
Стань неперевершеним QA спеціалістом! Стань технічною хрещеною феєю, яка оберігає від помилок і багів. Використай цей шанс!
Дізнатись про курс
определяет количество бит на канал цвета (также есть значения и );
(, ) — отношения ширины к высоте: ;
— оценивает режим отображения страницы: портретный () или альбомный ();
(, ) — это разрешение устройства ввода: требуемое, минимальное и максимальное; измеряется в dpi, dpcm или dppx.
Мультимедийные функции (Media Queries Level 4)
В «Media Queries Level 4» добавлены следующие новые функции, которые, возможно, будут реализованы в браузерах:
-
scripting (определяет используются ли языки сценариев, такие как JavaScript в текущем документе).
Значения:- enabled (скрипты доступны в текущем документе).
- initial-only (скрипты доступны только во время первоначальной загрузке страницы, а не после).
- none (скрипты полностью недоступны в текущем документе).
-
pointer (используется для запроса о наличии и правильности указывающего устройства, такого как мышь. Если устройство имеет несколько механизмов ввода, то функция указателя должна отражать характеристики «первичного» механизма входного сигнала, который определяется браузером пользователя).
Значения:- none (основной механизм ввода устройства не включает в себя указательное устройство).
- coarse (основным механизмом ввода устройства входит указательное устройство ограниченной точности, например, сенсорные экраны и системы обнаружения движения по типу Kinect — периферийные устройства для Xbox).
- fine (основной механизм ввода устройства включает в себя точное указывающее устройство, например, мыши, тачпады и устройства для рисования стилусом).
-
any-pointer (аналогичен pointer, но используется для запроса возможности любого доступного механизма ввода).
Значения:
none | coarse | fine -
hover (используется для запроса на способность пользователя навести курсор на элемент на странице. Если устройство имеет несколько механизмов ввода, то функция должна отражать характеристики «первичного» механизма входного сигнала, который определяется браузером пользователя).
Значения:- none (указывает, что основное указательное устроство не может навести курсор на элемент на странице, например, сенсорные экраны и экраны, которые используют для рисования стилусом).
- hover (указывает, что основное указательное устроство может навести курсор на элемент на странице, например, мыши и устройства с физической точкой на экране, как контроллер Nintendo для Wii.).
-
any-hover (аналогичен hover, но используется для запроса возможности любого доступного механизма наведения).
Значения:
none | hover -
color-gamut (описывает примерный диапазон цветов, которые поддерживаются UA и выходными устройствами).
Значения:- srgb (выходное устройство может поддерживать примерно диапазон sRGB или более).
- p3 (выходное устройство может поддерживать примерно диапазон, указанный DCIP3 цветового пространства или более).
- rec2020 (выходное устройство может поддерживать примерно диапазон, указанный в ITU-R рекомендации BT.2020 цветового пространства или более).
-
update (функция средства обновления используется для запроса на способность устройства вывода изменить внешний вид содержимого после его рендеринга).
Значения:- none (макет не может быть обновлен, например, для документов, напечатанных на бумаге).
- slow (макет может динамически меняться в соответствии с обычными правилами CSS, но выходное устройство не в состоянии достаточно быстро отобразить изменения, чтобы восприниматься как плавная анимация, например: e-ink экраны).
- fast (макет может динамически изменяться в соответствии с обычными правилами CSS и выходное устройство не ограничено в скорости, поэтому такие эффекты как CSS анимация могут быть использованы, например: экраны компьютера.).
-
overflow-block (определяет как выходные устройства обрабатывают содержимое, которое не помещается в область просмотра по оси блока)
Значения:- none (любое переполнение контента просто не отображается, например, рекламные щиты).
- scroll (позоляет пользователю прокрутить содержание, например, экраны компьютеров).
- optional-paged (позволяет пользователям прокрутить переполненное содержимое, например, слайд-шоу).
- paged (содержимое разделено на отдельные страницы, содержимое, выходящее за пределы одной страницы в оси блока отображается на следующей странице, например, принтеры или устройства для чтения).
-
overflow-inline (описывает поведение устройства, когда содержимое превышает начальный содержащий блок по inline оси.)
Значения:- none (любое переполнение контента просто не отображается).
- scroll (позоляет пользователю прокрутить содержание).
Media Query Breakpoints
Breakpoints are used to set the points where a website will apply a media query.
When you’re designing a media query, you may ask yourself the question: what sizes should I use to set my media queries? This is a reasonable question, because when you are just starting with responsive web design you may find it difficult to figure out the sizes of the devices on which your website should render.
There are lists on the internet that target specific screen sizes, which can be useful in setting the breakpoints for your media queries. However, due to the wide range of devices that are out there—which all have their own screen sizes and specifications—these lists usually do not cover all the main points.
The best way to choose when a media query should trigger is to look through your website for any places where elements become squashed or trimmed. So, if you see an element that is not fully visible on a mobile device, you know that you may need to add a breakpoint.
Then, once you have identified these points, you can write custom media rules. For example, you may realize that a <div> tag does not render correctly on devices whose width is less than 500px. In that case, you’ll want to write a media query to design custom styles for this resolution.
However, to get you started, here is a list of breakpoints which can help you target the main devices which may be used to visit your website:
- Most phones: @media screen and (max-width: 600px) {}
- Portrait tablets and large phones: @media screen and (min-width: 600px) {}
- Landscape tablets: @media screen and (min-width: 768px) {}
- Laptops and desktop machines: @media screen (min-width: 992px) {}
- Large laptops and desktop machines: @media screen (min-width: 1200px) {}
These rules should help you get started in determining the breakpoints for your media queries, but you may end up making a few changes to suit the particular needs of your website.
The @media syntax
Creating a Media query begins with the keyword followed by one or more conditions. The condition can be a device type or a requirement for a certain device-specific characteristic. The requirement for a certain characteristic is written in parentheses.
Combining multiple conditions is done using logical operators.
Once a query is composed, the styles specified in it will be applied only when the final result of the function returns as true.
Here’s an example of a media query with a single condition:
Here’s an example of a media query with multiple conditions:
The above example would then only apply the style to a smaller device that fits within the parameters minimum of 570px viewport width and a maximum of 768px.
How Does Responsive Design Work?
The basis of responsive design is media queries: a CSS technology that can apply styles according to metrics such as the output type (screen, printer, or even speech), screen dimensions, display aspect ratio, device orientation, color depth, and pointer accuracy. Media queries can also take user preferences into account, including reduced animations, light/dark mode, and higher contrast.
The examples we’ve shown demonstrate media queries using screen width only, but sites can be considerably more flexible. Refer to the full set of options on MDN for details.
Media query support is excellent and has been in browsers for more than a decade. Only IE8 and below have no support. They ignore styles applied by media queries, but this can sometimes be a benefit (read more in the Best Practices section below).
There are three standard ways to apply styles using media queries. The first loads specific stylesheets in HTML code. For example, the following tag loads the wide.css stylesheet when a device has a screen that is at least 800 pixels wide:
Secondly, stylesheets can be conditionally loaded in CSS files using an at-rule:
More typically, you’ll apply media queries in stylesheets using a @media CSS at-rule block that modifies specific styles. For example:
Developers can apply whichever media query rules are necessary to adapt the layout of a site.
# Basic Example
The above media query specifies two conditions:
- The page must be viewed on a normal screen (not a printed page, projector, etc).
- The width of the user’s view port must be at least 720 pixels.
If these conditions are met, the styles inside the media query will be active, and the background color of the page will be sky blue.
Media queries are applied dynamically. If on page load the conditions specified in the media query are met, the CSS will be applied, but will be immediately disabled should the conditions cease to be met. Conversely, if the conditions are initially not met, the CSS will not be applied until the specified conditions are met.
In our example, if the user’s view port width is initially greater than 720 pixels, but the user shrinks the browser’s width, the background color will cease to be sky blue as soon as the user has resized the view port to less than 720 pixels in width.
Средства, которые относятся к медиа, и их особенности
Выделяют семь средств медиакоммуникации. Каждое из них обладает своими особенностями, которые нужно учитывать в работе.
Массмедиа
К нему относятся средства массовой информации со всеми доступными каналами. Например, телевидение, периодическая печать, радио, кабельное телевидение. В зависимости от способа распространения выделяют несколько видов массмедиа:
- печатные;
- аудиальные;
- визуальные;
- аудиовизуальные.
За последние годы наибольшую популярность приобрел аудиовизуальный способ распространения массмедиа, позволяющий осваивать информацию комплексно. Кроме того, эти каналы коммуникации используют для подачи разных типов контента: от коммерческого до развлекательного.
Директ-медиа
К директ-медиа относятся элементы новых медиа: смартфоны, планшеты, электронная почта — все, что связано с интернет-коммуникациями. Частным примером считают онлайн-издания, так как они пришли из области журналистики. Понятие обозначает процесс развития технологий, помогающих налаживать новые способы коммуникации.
Медианосители
В эту категорию входят отдельные носители текстовой, аудио-, видеоинформации, презентаций. К их числу относят флешки, диски, облачные серверы для хранения данных. Подобные элементы могут содержать сведения о работе компании, ее продуктах, рекламном продвижении.
Социальные медиа
С помощью этих средств коммуникации бренд выстраивает диалог с аудиторией: социальные сети, сайты, корпоративные издания, блоги. При работе с ними используют разные способы презентации информации о продуктах, политике компании, ее миссии, ценностях.
Мультимедиа
Дословно «мультимедиа» переводится как «множество сред». Это означает формат передачи данных, когда информация транслируется сразу несколькими способами и через разные каналы: через визуальную графику, звуковую дорожку, видеоряд. Мультимедиа позволяет выбрать оптимальный способ подачи информации.
Медиамаркетинг
Это маркетинг, в котором продвижение товаров и услуг проходит с помощью СМИ. Цель медиамаркетинга — не просто реклама, а установка эффективной коммуникации с потребителем в онлайне и ее постоянная поддержка.
Медиареклама
Медиареклама представляет собой продвижение продукта через размещение информационных и промоматериалов на медианосителях. Она предполагает:
- Анализ целевой аудитории для СМИ.
- Построение коммуникации с аудиторией с помощью медиа.
- Медиамикс — использование разных видов медиа в рекламной кампании. Его применяют на этапе медиапланирования, чтобы сравнить плюсы и минусы нескольких медианосителей.
- Анализ показателей: количество и частота показов, охват, узнаваемость, запоминаемость.
Media Query Syntax
To declare a media query in CSS, you need to use the
rule. This rule allows you to execute a block of CSS properties only if a certain condition evaluates to true.
Here is the basic syntax for a CSS media query:
@media media-type and (media-rule) { // CSS styles }
Here are the main components of this media query:
-
@media
instructs the browser to create a media query.
-
media-type
is the type of media the code will be used for (i.e. screen or print).
-
and
is a logical operator that we need to use when specifying both a media type and a media rule.
-
media-rule
is the statement that must evaluate to true in order for the CSS in the media query to execute.
-
CSS styles
are the rules that will be applied to a web element if the media-rule evaluates to true.
There are four media types that can be used with a media query. These are all, print, screen, and speech. By default, the value
is used, and multiple media types can be specified by separating each type using a comma.
Basic syntax of a media query
Here is the basic syntax for a media query in CSS:
Let’s break down what this syntax means.
The is a type of in CSS. These rules will dictate what the CSS will look like based on certain conditions.
The media type refers to the category of media for the device. The different media types include , , and .
- all — works for all devices
- print — works for devices where the media is in print preview mode
- screen — works for devices with screens
- speech — works for devices like screen readers where the content is read out loud to the user
According to documentation,
You can choose to omit the media type and use this syntax instead.
The media feature refers to the characteristics of the browser which include height and width of the viewport, orientation or aspect-ratio. For a complete list of the possible media features, please .
For this article, we are going to focus on the width media feature.
If you wanted to create more complex media queries, then you can use logical operators.
- — This operator is used to join multiple media features. If all of the media features are true then the styles inside the curly braces will be applied to the page.
- — This operator reverses a true query into a false and a false query into a true.
- (comma) — This operator will separate multiple media features by commas and apply the styles inside the curly brace if one of the conditions is true.
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»>
Flexible Image Gallery
To make your image gallery responsive, you need to use a combination of CSS styling properties like , , and .
In our example, the original four columns become two columns or even a single column on the smallest screens:
Example Copy
Pros
- Easy to use with a learn-by-doing approach
- Offers quality content
- Gamified in-browser coding experience
- The price matches the quality
- Suitable for learners ranging from beginner to advanced
Main Features
- Free certificates of completion
- Focused on data science skills
- Flexible learning timetable
EXCLUSIVE: 50% OFF Pros
- Simplistic design (no unnecessary information)
- High-quality courses (even the free ones)
- Variety of features
Main Features
- Nanodegree programs
- Suitable for enterprises
- Paid Certificates of completion
15% OFF Pros
- Easy to navigate
- No technical issues
- Seems to care about its users
Main Features
- Huge variety of courses
- 30-day refund policy
- Free certificates of completion
AS LOW AS 14.99$