Условия в стилях css

CSS Conditional Rules

CSS Conditional Rules, как следует из названия, являются условными конструкциями, которые можно применять в самом CSS. Они реализуют проверку поддержки свойств текущим браузером с возможностью группировать условные выражения с помощью логических операторов and , or и not . В этом посте хотелось бы рассказать, кроме прочего, о синтаксисе этого модуля CSS3 и текущей поддержке его браузерами.

Что нового?

  • это проверка поддержки указанных свойств браузером, а не проверка имени и версии браузера.
  • это реализация условных конструкций прямо в CSS, таким образом, мы можем управлять «потоком применения» свойств CSS, а не выбираем в HTML-коде какие заранее подготовленные для разных браузеров файлы стилей подключить; проще говоря, если нам нужно реализовать свойство, неподдерживаемое всеми необходимыми браузерами, у нас появляется гибкий инструмент для degradation.

А на практике?

Синтаксис прост. Например, у нас есть свойство font-size , в котором мы хотим использовать функцию calc() для вычисления размера шрифта, а в качестве аргумента этой функции мы хотим передать выражение, которое вычисляет размер шрифта от размера шрифта корневого элемента body . Но сколько браузеров сегодня это поддерживает? Маловато. А что делать с остальными? С использованием условий CSS3 вопрос получит такой ответ:

body < font-size: 14px; >@supports (font-size: calc(1rem + 12px)) < h1 < font-size: calc(1rem + 12px); >> @supports not (font-size: calc(1rem + 12px)) < h1 < font-size: 26px; >> 

Пример избыточен, но зато видна логика. Правило @supports предваряет условную конструкцию. Условным выражением считается то, что находится в круглых скобках, при этом круглые скобки всегда обязательны. Мы можем комбинировать условные выражения с помощью операторов and и or , а также отрицать выражения с помощью not .

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

/* Это неправильный код! */ @supports (transition-property: color) or (animation-name: foo) and (transform: rotate(10deg))

Казалось бы, синтаксис верный, чего же боле? Проблема в том, что эту конструкцию можно трактовать по разному. Что мы имели ввиду: нам нужна поддержка [( transition или animation ) и ( transform )] или [( transition ) или ( animation и transform )]? Неизвестно. Именно поэтому мы должны использовать круглые скобки так же, как я сделал это только что, описывая возможные варианты. Нижеследующие варианты того же кода будут правильными.

@supports ((transition-property: color) or (animation-name: foo)) and (transform: rotate(10deg)) < >@supports (transition-property: color) or ((animation-name: foo) and (transform: rotate(10deg)))

Ну и когда?

А теперь о статусе поддержки на данный момент. Сама спецификация находится в статусе рабочего черновика. В стабильных версиях сегодня это не поддерживает никто. 3 августа поддержка @supports появилась в Firefox 17.0a1, то есть сейчас она есть в ветке Firefox Aurora и где-нибудь в октябре будет в Beta. Про поддержку другими браузерами я пока ничего не слышал (быть может, кто-то из хабражителей подскажет). В самом же Firefox 17 эта опция может быть отключенной в настройках, если разработчики решат, что спецификация еще недостаточно стабильна.

Читайте также:  Exaple of pre tag.

UPD: в бета-версии Opera 12.10 появилась поддержка @supports.

Источник

Написание логики в CSS

KKKK

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

Структуры управления

Более традиционные языки общего назначения (например, JavaScript) предоставляют нам такие инструменты, как условия ( if/then ), циклы ( for , while ), логические элементы ( === , && , и т. д.) и переменные. Эти структуры называются в CSS по-разному, их синтаксис сильно отличается, чтобы лучше соответствовать конкретному варианту использования при оформлении документа, а некоторые из них просто не были доступны в CSS еще несколько лет назад.

Переменные

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

Источник

CSS If Statement

A Cascading Style Sheet consists of the code that is used to add style to the HTML code. This contains several properties and effects to the HTML content so that the display looks aesthetic. HTML and CSS work together to create a web page front-end. The effects that are introduced by CSS are the font color, size, alignment, hover effect, etc. This guide will cover some logical parts of the HTML and CSS discussion.

CSS consists of three types. Here, the internal CSS is used to carry out all the applied effects. For the CSS treatment purpose, we need the internal and external CSS.

If-else Statement

The if or if-else statement is the logical code that is provided to any programming language. This code is used at the point when we want to apply any one condition from two or more choices. This statement is also known as a conditional statement. The phenomenon works in such a way that when the condition applied by the program is true, a specific piece of code gets executed. Otherwise, they go to the next line, either the “else” part or the “if-else” part. The logic is applied to them if the condition is executed and it decides whether to go for the next else part or go outside the “if” body.

If Statement

We are not capable of using an “if” statement in CSS as CSS does not support logic. But other methodologies are used alternatively to this “if” statement. The “if” statement in CSS works like using a simple class declaration in the internal or external CSS. The class names are only mentioned when we need to apply all the effects mentioned in the class. We will use this concept in the different examples of our code.

Читайте также:  Product Card

CSS If statement syntax:

The syntax contains the statement in which a condition related to the items is provided. In CSS, since there is no concept of using CSS directly, we use the classes and declare them inside the HTML tags and add the CSS to these classes.

Example 1: If Statement Style in CSS Code

This example is the simple way of using the “if” statement style in the CSS code. First, consider the HTML body tags. We use the basic unit of HTML content to display this concept as a web page, which is the text. The heading is applied first. This heading is given an inline CSS property whose style is added to the tag with the font color property.

Then, we use a simple heading. We use a span tag to add two paragraphs to the webpage. Both these spans are accompanied by the class names as the internal CSS property CSS class declaration.

After that, close the body. Now, we will see how the CSS classes are declared as a concept of the “if-else” statement.

As we mentioned earlier, the CSS class declaration somehow works on the same “if-else” statement. Now, see the class declaration of the “color-line1” and “color-line2” inside the style tag.

The first condition is applied as purple color on line1. For the line2, the orange color is applied. Whatever is the sequence of the CSS class declaration, but according to the lines, the effect is applied on the HTML tags respectively.

After that, save the code with an html extension. This extension takes them to execute in the browser within a web page.

Upon the execution of the page, you will see that a web page is created with a heading that was declared with an inline CSS. Then, all three contents, a heading, and span are declared according to the HTML tags having the class name inside them.

Example 2: If-else Statement Through SAAS

The syntactically awesome style sheet is a type of CSS that gives the true statement that contains the conditions they apply in the style that converts the syntax of CSS into the W3C CSS syntax. It also assists to create a style sheet faster as compared to the manual CSS.

The main concept behind the usage of this approach is that three different files are used with different extensions. We first create a “.scss” file and then the code behind it is converted into the “.css” extension. Then, we can easily see the changes because of this act.

Читайте также:  Table padding right css

We first consider the HTML body code. A div is created here with a class name “container”. A simple heading and a paragraph are declared inside the div body.

HTML Body Code:

Now, consider the code that is present inside the SASS file having been saved with a “.scss” extension.

The syntax shows that the paragraph tag is targeted. All the options for the paragraph are written with “2” at the start.

According to SAAS, the number of options is displayed in front of the HTML contents. The condition that makes any sense or can be true. Then, the property written inside that condition is applied to the HTML content. The first option is as follows:

It is stated that if two numbers are added to give the resultant value and is true, apply the border feature to the paragraph. This condition seems to be true as both “2” are combined to form a 4.

Another condition displays that if the first value is less than the second one, a border of specified size is applied to the paragraph. This condition is not true, so it is not applied. Moving forward to the next condition.

This condition contains no value. If the condition is null, a border type that is double a specified size is applied. You can also apply any CSS property other than the border property. The number of the condition can also be changed.

Now, we convert this code into the CSS code simply, this contains the following code.

Amongst all the conditions, the first one was true, so it is picked and applied to the HTML paragraph.

The border of 2px solid is applied. When we execute the code, we get the web page. Take a look at the little snippet attached here:

You can see that a border is applied to the paragraph according to the true condition.

Conclusion

In this article, we tried to explain the concept of working on an “if” statement in HTML and CSS. As we elaborated in the previous discussion, there is no standard syntax or any approach to utilize the if-statement directly in the CSS tags. But we use it accordingly like the SAAS. The SAAS contains the properties according to the conditions. If the logic given in the condition gets satisfied, then the specified property is applied to the HTML content respectively. First, we gave a brief introduction about the if-statement in CSS. Then, by using two examples, the working of this concept is explained.

About the author

Aqsa Yasin

I am a self-motivated information technology professional with a passion for writing. I am a technical writer and love to write for all Linux flavors and Windows.

Источник

Оцените статью