Using CSS @Variables [duplicate]

China☆狼群 提交于 2019-12-04 18:19:16

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!