Css media mobile only one

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

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

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

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

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

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

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

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

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

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

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

@media speech and (aspect-ratio: 11/5)  . > 

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

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

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

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

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

and

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

@media (min-width: 30em) and (orientation: landscape)  . > 

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

@media screen and (min-width: 30em) and (orientation: landscape)  . > 

comma-separated lists

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

@media (min-height: 680px), screen and (orientation: portrait)  . > 

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

not

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

@media not all and (monochrome)  . > 

. so that the above query is evaluated like this:

@media not (all and (monochrome))  . > 
@media (not all) and (monochrome)  . > 

As another example, the following media query:

@media not screen and (color), print and (color)  . > 
@media (not (screen and (color))), print and (color)  . > 

only

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

link rel="stylesheet" media="only screen and (color)" href="modern-styles.css" /> 

Смотрите также

Found a content problem with this page?

This page was last modified on 26 мая 2023 г. by MDN contributors.

Your blueprint for a better internet.

Источник

Responsive Web Design — Media Queries

It uses the @media rule to include a block of CSS properties only if a certain condition is true.

Example

If the browser window is 600px or smaller, the background color will be lightblue:

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%:

@media only screen and (max-width: 768px) /* For mobile phones: */
[class*=»col-«] width: 100%;
>
>

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: */
[class*=»col-«] width: 100%;
>

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 ( col- and col-s- ):

/* For mobile phones: */
[class*=»col-«] 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:

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

/* 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)

Orientation: Portrait / Landscape

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:

Example

The web page will have a lightblue background if the orientation is in landscape mode:

Hide Elements With Media Queries

Another common use of media queries, is to hide elements on different screen sizes:

Example

/* If the screen size is 600px wide or less, hide the element */
@media only screen and (max-width: 600px) div.example display: none;
>
>

Change Font Size With Media Queries

You can also use media queries to change the font size of an element on different screen sizes:

Variable Font Size.

Example

/* If the screen size is 601px or more, set the font-size of

to 80px */
@media only screen and (min-width: 601px) div.example font-size: 80px;
>
>

/* If the screen size is 600px or less, set the font-size of to 30px */
@media only screen and (max-width: 600px) div.example font-size: 30px;
>
>

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.

Источник

Читайте также:  Generic Servlet Demo
Оцените статью