问题
I am trying to use CSS Variables. I look online for tutorials and all of them worked so far.
Here's my CSS:
@variables {
defaultColor: #8E5050;
defaultBackGround: #E1DBC3;
}
body {
background: var(defaultBackGround);
}
a {
color: var(defaultColor);
}
I also tried:
body {
background: @defaultBackGround;
}
a {
color: @defaultColor;
}
None of them works, What am I doing wrong? Thanks
回答1:
I would use a CSS preprocessor such as Sass or Less.
回答2:
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. :)
回答3:
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.
回答4:
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);
}
来源:https://stackoverflow.com/questions/7583076/using-css-variables