Using CSS @Variables [duplicate]

不羁的心 提交于 2019-12-03 12:01:47
Petah

I would use a CSS preprocessor such as Sass or Less.

The variables you are using are not part of the normal CSS specification. It looks like you are writing in some CSS framework.

If you do want to use pure CSS, you are stuck with setting the values of colors / margins / padding manually every time. But a good "Search & replace"-function in your favorite text editor may help you there. :)

If you want to use these variables, @Petah has the right answer for you. :)

Use Native CSS3 Variables!

Variables are actually a native feature in CSS3 - you can read the spec at MDN. However, they are still a relatively new feature, so you may want to check out the Browser Support charts here before using them.

That being said, CSS Variables are supported by the latest versions of Chrome, Firefox, Opera, Safari and Microsoft Edge.

The following code shows an example of how CSS variables can be used:

:root {
    --name: #ff0000;
}
p {
    color: var(--name);
}

How does this work?

Variables can be used if they are defined on the parent container of the element - here I use :root so that the variable is accessible everywhere.

A variable can be defined using --name:content; where name is the name of the variable and content is the contents of the variable (this can be a color, like #ff0000, a size like 1em, or one of many more possible values).

Then, simply use var(--name) instead of a property in your CSS code, where name is again the name you called the variable.

From what I understand, variables aren't fully supported yet, but this is how you will set them when they are:

/* declare in :root with the usual browser prefixes */
:root {
  var-myVariableColor: #f00;
  -webkit-var-myVariableColor: #f00;
  -moz-var-myVariableColor: #f00;
  -ie-var-myVariableColor: #f00;
}

/* to reference encase in var() */
body {
  background-color: var(myVariableColor);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!