你可以在 CSS 中使用 if/else 条件吗?
我想在我的 CSS 中使用条件.
I would like to use conditions in my CSS.
这个想法是我有一个变量,当网站运行时我会替换它以生成正确的样式表.
The idea is that I have a variable that I replace when the site is run to generate the right style-sheet.
我想要它根据这个变量改变样式表!
I want it so that according to this variable the style-sheet changes!
看起来像:
[if {var} eq 2 ]
background-position : 150px 8px;
[else]
background-position : 4px 8px;
这可以吗?你是怎么做到的?
Can this be done? How do you do this?
推荐答案
不是传统意义上的,但如果您可以访问 HTML,则可以为此使用类.考虑一下:
Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:
<p class="normal">Text</p>
<p class="active">Text</p>
在您的 CSS 文件中:
and in your CSS file:
p.normal {
background-position : 150px 8px;
}
p.active {
background-position : 4px 8px;
}
这就是 CSS 的方法.
还有像 Sass 这样的 CSS 预处理器.您可以在此处使用 条件,如下所示:p>
Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:
$type: monster;
p {
@if $type == ocean {
color: blue;
} @else if $type == matador {
color: red;
} @else if $type == monster {
color: green;
} @else {
color: black;
}
}
缺点是,您必须对样式表进行预处理,并且条件是在编译时而不是运行时评估的.
Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.
CSS 的一个新特性是 自定义属性(又名 CSS 变量).它们在运行时进行评估(在支持它们的浏览器中).
A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).
有了他们,你可以做一些事情:
With them you could do something along the line:
:root {
--main-bg-color: brown;
}
.one {
background-color: var(--main-bg-color);
}
.two {
background-color: black;
}
<小时>
最后,您可以使用您最喜欢的服务器端语言预处理您的样式表.如果你使用 PHP,提供一个 style.css.php
文件,看起来像这样:
Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php
file, that looks something like this:
p {
background-position: <?php echo (@$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}
在这种情况下,您会受到性能影响,因为缓存这样的样式表会很困难.
In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.
相关文章