你可以在 CSS 中使用 if/else 条件吗?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1129699/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 20:48:51  来源:igfitidea点击:

Can you use if/else conditions in CSS?

cssstylesheetconditional-statements

提问by Haim Evgi

I would like to use conditions in my CSS.

我想在我的 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!

我想要它根据这个变量样式表改变!

It looks like:

看起来像:

[if {var} eq 2 ]
    background-position : 150px 8px;
[else]
    background-position : 4px 8px; 

Can this be done? How do you do this?

这能做到吗?你怎么做到这一点?

回答by Boldewyn

Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:

不是传统意义上的,但是如果您可以访问 HTML,则可以为此使用类。考虑一下:

<p class="normal">Text</p>

<p class="active">Text</p>

and in your CSS file:

并在您的 CSS 文件中:

p.normal {
  background-position : 150px 8px;
}
p.active {
  background-position : 4px 8px;
}

That's the CSSway to do it.

这就是CSS 的方式。



Then there are CSS preprocessors like Sass. You can use conditionalsthere, which'd look like this:

然后是像Sass这样的 CSS 预处理器。你可以在那里使用条件,它看起来像这样:

$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.

缺点是,您必须对样式表进行预处理,并且条件是在编译时而不是运行时评估的。



A newer feature of CSS proper are custom properties(a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).

CSS 本身的一个新特性是自定义属性(又名 CSS 变量)。它们在运行时进行评估(在支持它们的浏览器中)。

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;
}


Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.phpfile, that looks something like this:

最后,您可以使用您最喜欢的服务器端语言预处理您的样式表。如果您使用的是 PHP,请提供一个style.css.php文件,如下所示:

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.

在这种情况下,您将受到性能影响,因为缓存这样的样式表将很困难。

回答by markus

Below is my old answer which is still valid but I have a more opinionated approach today:

下面是我的旧答案,它仍然有效,但我今天有一个更固执的方法:

One of the reasons why CSS sucks so much is exactly that it doesn't have conditional syntax. CSS is per se completely unusable in the modern web stack. Use SASS for just a little while and you'll know why I say that. SASS has conditional syntax... and a LOT of other advantages over primitive CSS too.

CSS 如此糟糕的原因之一正是它没有条件语法。CSS 本身在现代 Web 堆栈中完全无法使用。使用 SASS 一会儿,你就会知道我为什么这么说。SASS 具有条件语法……以及与原始 CSS 相比的许多其他优势。



Old answer (still valid):

旧答案(仍然有效):

It cannot be done in CSS in general!

一般在 CSS 中是做不到的!

You have the browser conditionals like:

您有浏览器条件,例如:

/*[if IE]*/ 
body {height:100%;} 
/*[endif]*/

But nobody keeps you from using Javascript to alter the DOM or assigning classes dynamically or even concatenating styles in your respective programming language.

但是没有人阻止您使用 Javascript 来更改 DOM 或动态分配类,甚至在您各自的编程语言中连接样式。

I sometimes send css classes as strings to the view and echo them into the code like that (php):

我有时将 css 类作为字符串发送到视图并将它们回显到这样的代码中(php):

<div id="myid" class="<?php echo $this->cssClass; ?>">content</div>

回答by yeedle

You can use calc()in combination with var()to sort of mimic conditionals:

您可以calc()结合使用var()来模拟条件:

:root {
--var-eq-two: 0;
}

.var-eq-two {
    --var-eq-two: 1;
}

.block {
    background-position: calc(
        150px * var(--var-eq-two) +
        4px * (1 - var(--var-eq-two))
    ) 8px;
}

concept

概念

回答by RaYell

You could create two separate stylesheets and include one of them based on the comparison result

您可以创建两个单独的样式表,并根据比较结果包含其中之一

In one of the you can put

在其中一个你可以放

background-position : 150px 8px;

In the other one

在另一个

background-position : 4px 8px;

I think that the only check you can perform in CSS is browser recognition:

我认为您可以在 CSS 中执行的唯一检查是浏览器识别:

Conditional-CSS

条件CSS

回答by beggs

Set the server up to parse css files as PHP and then define the variable variable with a simple PHP statement.

将服务器设置为将 css 文件解析为 PHP,然后使用简单的 PHP 语句定义变量变量。

Of course this assumes you are using PHP...

当然,这假设您使用的是 PHP ...

回答by Peter

I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.

我很惊讶没有人提到 CSS 伪类,它们也是 CSS 中的一种条件。你可以用它做一些非常高级的事情,而无需一行 JavaScript。

Some pseudo-classes:

一些伪类:

  • :active - Is the element being clicked?
  • :checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
  • :empty - Is the element empty?
  • :fullscreen - Is the document in full-screen mode?
  • :focus - Does the element have keyboard focus?
  • :focus-within - Does the element, or any of its children, have keyboard focus?
  • :has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
  • :hover - Does the mouse hover over this element?
  • :in-range/:out-of-range - Is the input value between/outside min and max limits?
  • :invalid/:valid - Does the form element have invalid/valid contents?
  • :link - Is this an unvisited link?
  • :not() - Invert the selector.
  • :target - Is this element the target of the URL fragment?
  • :visited - Has the user visited this link before?
  • :active - 元素是否被点击?
  • :checked - 是否选中了单选框/复选框/选项?(这允许通过使用复选框进行条件样式!)
  • :empty - 元素是否为空?
  • :fullscreen - 文档是否处于全屏模式?
  • :focus - 元素是否有键盘焦点?
  • :focus-within - 元素或其任何子元素是否具有键盘焦点?
  • :has([selector]) - 元素是否包含与 [selector] 匹配的子元素?(遗憾的是,任何主要浏览器都不支持。)
  • :hover - 鼠标悬停在这个元素上吗?
  • :in-range/:out-of-range - 输入值是否在最小和最大限制之间/之外?
  • :invalid/:valid - 表单元素是否包含无效/有效内容?
  • :link - 这是一个未访问的链接吗?
  • :not() - 反转选择器。
  • :target - 这个元素是 URL 片段的目标吗?
  • :visited - 用户以前访问过这个链接吗?

Example:

例子:

div { color: white; background: red }
input:checked + div { background: green }
<input type=checkbox>Click me!
<div>Red or green?</div>

回答by Kurkula

You can use not instead of if like

你可以使用 not 而不是 if like

.Container *:not(a)
{
    color: #fff;
}

回答by amichai

You can add container div for all your condition scope.

您可以为所有条件范围添加容器 div。

Add the condition value as a class to the container div. (you can set it by server side programming - php/asp...)

将条件值作为类添加到容器 div 中。(你可以通过服务器端编程来设置——php/asp...)

<!--container div-->
<div class="true-value">
   <!-- your content -->
   <p>my content</p>
   <p>my content</p>
   <p>my content</p>
</div>

Now you can use the container class as a global variable for all elements in the div using a nested selector, without adding the class to each element.

现在,您可以使用嵌套选择器将容器类用作 div 中所有元素的全局变量,而无需将类添加到每个元素。

.true-value p{
   background-color:green;
}
.false-value p{
   background-color:red;
}

回答by hadi teo

As far as i know, there is no if/then/else in css. Alternatively, you can use javascript function to alter the background-position property of an element.

据我所知,css 中没有 if/then/else。或者,您可以使用 javascript 函数来更改元素的 background-position 属性。

回答by Johan

This is a little extra info to the Boldewyn answer above.

这是上面 Boldewyn 答案的一些额外信息。

Add some php code to do the if/else

添加一些 php 代码来执行 if/else

if($x==1){
  print "<p class=\"normal\">Text</p>\n";
} else {
  print "<p class=\"active\">Text</p>\n";
}