Variables in css files

Основные варианты использования CSS-переменных (Custom Properties)

CSS Variables или CSS Custom Properties уже давно используются в разработке и поддерживаются большинством популярных браузеров. Если у вас нет обязательного требования разрабатывать под IE, то вполне вероятно, вы уже успели оценить их преимущества.

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

Варианты использования

1. Определение переменных

Начнём с базовых вещей, а именно: как определять переменные. Стоит помнить, что их можно определить как в корневом элементе :root (переменные будут доступны по всему приложению), так и внутри любого селектора (будут доступны только для выбранного элемента и его дочерних элементов):

2. Переопределение переменных

В примере показан кейс, когда при наведении на элемент, должен меняться цвет. Для этого мы переопределяем переменную —color по событию :hover :

Второй пример показывает переопределение переменной в @media выражении. К сожалению, мы не можем вынести 1024px в переменную и использовать ее в @media — это является одним из ограничений CSS переменных.

:root < --color: green; >body < background-color: var(--color); >@media (max-width: 1024px) < :root < --color: red; >>

3. Локальный fallback

Представьте, что вы вызываете переменную —color-green , а ее не существует. Страшного не случится, но заданное CCS-свойство не отработает. Для подстраховки можно задать резервное значение вторым аргументом. Это значение также может быть CSS-переменной:

Читайте также:  Параметры в enum java

4. Привязка переменных

При объявлении переменных могут использоваться другие переменные:

5. Переменные в calc()

В calc() можно перемножать числа со значениями в единицах измерения, н-р: px .

На выходе получим результирующее значение в той единице измерения, на которую умножили.

В примере показано, как перемножается 2 на 10px и в итоге получается 20px. Не важно, используем мы для этого обычные значения или CSS-переменные — результат будет одинаковый:

К примеру, у нас есть переменная —font: 20 . Но без указания единицы измерения мы не сможем ее корректно использовать в font-size .

Это можно решить с помощью calc() . Для преобразования числа в px , к примеру, достаточно умножить число на 1px в calc() :

6. Прозрачность в цветовых функциях

Задания цвета — самый распространенный кейс использования переменных.

Вот стандартный пример по использованию hex-цвета для определения значения переменной:

Часто бывает, что для цвета нужно задавать различную прозрачность. В CSS для этого есть:

Использование rgba()

При использовании переменных, удобнее это делать функцией rgba() , которая принимает 4 числовых значения для:

  1. Красного цвета
  2. Зеленого цвета
  3. Синего цвета
  4. Альфа-канала для задания прозрачности

На самом деле, внутри CSS допускается использовать практически всё (за небольшим исключением), даже код на JavaScript!

Поэтому, задание в переменной значения цветов для Red, Green, Blue — вполне допустимо.

Вызовем функцию rgba() с переменной —color-blue—rgb . Для rgba() не хватает четвертого аргумента задающего прозрачность — добавим его через запятую:

На выходе собираются аргументы для rgba() : значения из переменной и альфа-канала.

Использование hsla()

Кроме rgba() можно использовать и hsla() . Это не так удобно, но как вариант, можно попробовать.

  1. Определяем переменные с базовыми значениями для основных параметров hsla(): —hue , —saturation , —lightness , —opacity .
  2. При использовании, указываем все базовые параметры в селекторе.
  3. Меняем один / несколько переменных в селекторе (изменения коснутся только данного селектора и его дочерних элементов).

7. Переменные в SVG

С помощь переменных мы также можем изменять цвет внутри SVG: fill или stroke . Сложность заключается в том, что изображение SVG должно быть инлайново встроено на страницу, но при использовании сборщиков — это не проблема.

Итак, имеем SVG-элемент на странице, у которого в fill указана переменная —color :

И саму переменную —color в CSS:

Значение переменной можно переопределять при необходимых условиях: например, при событии hover на SVG:

Использование с JavaScript. API CSS Style Declaration

CSS переменные работают в runtime, в отличие переменных препроцессоров. Это значит, что мы можем получить к ним доступ в процессе работы приложения через JavaScript.

Рассмотрим, как можно работать с CSS переменными через JavaScript:

В CSS у нас есть 2 переменные:

// Получаем корневой элемент в DOM const root = document.querySelector(':root'); // Получаем "Вычисленные свойства" const rootStyles = getComputedStyle(root); // Получаем значение переменной по ее названию const color = rootStyles.getPropertyValue('--color'); // => 'green' // Изменяем значение переменной root.style.setProperty('--color', '#88d8b0'); // Удаляем CSS переменную root.style.removeProperty('--color');

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

Вычисленные свойства

В коде выше я затронул тему «Вычисленных свойств». Рассмотрим подробнее: для этого создадим небольшой пример:

Единицы измерения можно подразделить на абсолютные и относительные:

  • Абсолютные — это пиксели ( px ), которые привязываются к разрешению экрана.
  • Относительные (н-р: rem ) формируются относительно заданного параметра.

Для отображения, относительные единицы измерения должны быть преобразованы в абсолютные. Если мы откроем инспектор объектов в Google Chrome (или другом браузере) на вкладке «Elements», то сможем увидеть это преобразование:

  • В секции Styles — значения в том виде, в котором мы их указали в CSS (относительные).
  • В секции Computed — значения, приведенные к абсолютным единицам измерения. Функцией getComputedStyle в JavaScript мы как раз таки и получаем эти вычисленные значения.

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

Небольшую демку по изменению цветовой схемы можно посмотреть здесь.

Проверка поддержки переменных

@supports ( (--a: 0) ) < /* Стили с поддержкой переменных */ >@supports ( not (--a: 0) ) < /* Стили без поддержки переменных */ >
if (window.CSS && window.CSS.supports && window.CSS.supports('--a', 0)) < // Сценарии с поддержкой переменных >else < // Сценарии без поддержки переменных >

Достоинства и ограничения

  • Работают в runtime, в отличие от переменных препроцессоров
  • Можно обратиться из JavaScript
  • В именах обычных свойств CSS: var(—side): 10px
  • В значениях media-запросов: @media screen and (min-width: var(—desktop))
  • В подстановке URL: url(var(—image))

Заключение

Использование CSS-переменных еще один шаг к отказу от препроцессоров. Ждем реализации миксинов @apply на CSS и CSS Nesting Module!

Источник

How do I pass a variable to a CSS file?

I’m new to web design but a fairly apt programmer. I have a style.css and reference it on 4 different HTML pages. I want to change the background image and some other minor details for some pages (text size, height, etc). How do I pass a variable or get it to change for each. seems a waste to write a mostly similar CSS for each page. Thanks.

This answer covers an approach that should work for your question stackoverflow.com/a/45581552/5302749 CSS Custom Properties (aka variables) should do the trick for most use cases and has a HTML/CSS example.

«.seems a waste to write a mostly similar css for each page.» this is why you should have a common style sheet used on all your pages. Make that change on the one stylesheet, job done. Keep in mind both CSS and HTML are purely declarative, on their own they do noting, the are purely interpreted by the browser. They are seperate entities so there is no mechanism to pass variables between the two.

Thanks Jon and Brian. still dont have a clue what i’m doing but now i have a direction to learn about, thanks

2 Answers 2

Use class when you wish to apply a group of styles to many HTML elements, and unique id selectors for styling only a single element. You can also utilize CSS Variables for reusable values, there are a few ways to go about doing so. In general, you declare a custom variable by using a custom property name that begins with a double hyphen — , and a property value that can be any valid CSS value. Using var() allows us to insert the value of custom property (variable). If the custom property should be more than word, separate each word with a hyphen (kebab case).

So lets say you have four different HTML pages, you can use a single stylesheet (or multiple if you have a bunch of CSS and opt for a more modular approach) to define some custom variables and use them in the selectors you wish to style. Remember if you define a variable in style.css and try using it in another CSS file other-style.css it won’t be available. When using var() you can also define multiple fallback values if the given variable isn’t defined.

:root < --my-cool-prop: #f06; >.my-selector < color: var(--my-cool-prop, #000); /* black if --my-cool-prop is undefined */ >.some-selector < --some-prop: #fff; --some-other-prop: blue; color: var(--some-prop, red); /* red if --some-prop is undefined */ background-color: var(--some-other-prop, green); /* green if --some-other-prop is undefined */ >
 

Some title

Some other title

Источник

Using Variables in CSS

When I was first starting to learn web development, I remember being annoyed with writing the same hex code for a color over and over then finding out the color had to change and searching through code to find every instance. It was a huge pain! At the time, this was one of the pain points that made css preprocessors like Sass and Less so appealing since they allowed you to use variables in your styles. Fortunately, we live in a golden age of technology for web development where smart and passionate people are pushing the boundaries of what our tooling can do. As such, engineers have been hard at work making improvements to plain old css. One such improvement is the ability to use variables within your .css files! In this article, I’ll teach you how to use variables in your css files and what the limitations are.

Why are CSS variables important?

If you’ve been writing css for a while (or haven’t), I’m sure you’ve encountered a file with the same color value peppered in throughout the code. Even worse is when you have the same value used across several files. Simply having them there isn’t such a big deal, but what if you need to change them down the road? You’ll have to find every instance of that color and change it manually. It also means that if you are going to do something like a light and dark theme, you’ll have to write duplicate code for each theme based on class. Consider the code below:

body.light < background: #fff; color: #ff0000; font-size: 16px; >body.light button < background: #ff0000; color: #fff; border: 1px solid #ff0000; >body.dark < background: #222; color: #c0ffee; font-size: 16px; >body.dark button

Obviously the code above wouldn’t be that big of a deal to change, but if this file continued on and on with these colors you can imagine why it would be useful to make a change in one place and have it update everywhere. The code below shows how this code can work with variables.

You can see how concise the code is in the example. Because the values for variables can be reassigned, the —primary variable can be changed based on the body class rather than duplicating code with different values.

How to set up variables in CSS

To create a variable in your CSS, you need to decide what the scope of the variable will be. Variable creation is the same regardless of the scope, so the code below will apply anywhere although the selector may be different.

The example above shows how you can create an element with the sample-selector class. You will be able to access the —color variable from any child of the .sample-selector element. You can also create global css variables by using the :root selector which targets the html element. The —color assignment using the root selector would look like this:

Since the variable is assigned to the root element, you can use it anywhere in the styles with no problem. Going back to the idea of using themes, you could set a different variable value based on what class is assigned to the html element. That would look like this:

By using CSS variables in this way, you don’t have to add styles for both light and dark themes on each element. Instead, you can use and reuse a variable with a different value based on the theme class assigned to a given element.

Are there any limitations?

Although css variables have solved a lot of problems for front-end developers, it is not without flaws. If you’ve spent time writing SCSS or something similar, you may have used variables and mixins to handle media queries. This cannot be done with CSS variables which is a bit of a bummer. In addition, CSS variables can’t store a url. This would be useful if you had to reuse an image in different places, but it doesn’t work.

Conclusion

Overall, CSS variables are a very cool innovation within your styles. They make it very easy to not only write reusable styles, but update them or expand on them further down the road. I highly recommend checking them out in your next project and seeing what you think about them. Have questions? You can find me on Twitter at @iam_timsmith.

Источник

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