是否可以在另一个CSS规则中引用它?


101

例如,如果我具有以下HTML:

<div class="someDiv"></div>

和这个CSS:

.opacity {
    filter:alpha(opacity=60);
    -moz-opacity:0.6;
    -khtml-opacity: 0.6;
    opacity: 0.6; 
}
.radius {
    border-top-left-radius: 15px;
    border-top-right-radius: 5px;
    -moz-border-radius-topleft: 10px;
    -moz-border-radius-topright: 10px;    
}

.someDiv {
    background: #000; height: 50px; width: 200px;

/*** How can I reference the opacity and radius classes here
     so this div has those generic rules applied to it as well ***/

}

就像在脚本语言中一样,您具有通常在脚本顶部编写的通用函数,并且每次需要使用该函数时,只需调用该函数即可,而不必每次都重复所有代码。


无法更改HTML吗?
BoltClock

1
您只可以在中添加逗号分隔的类列表.radius,例如.radius, .another, .element{/* css*/}。这将为您节省额外的代码,但可能使其可读性降低。
Lekensteyn

Answers:


79

不,您不能从另一个引用一个规则集。

但是,您可以在样式表中的多个规则集上重用选择器,在单个规则集上使用多个选择器(通过用逗号分隔它们)。

.opacity, .someDiv {
    filter:alpha(opacity=60);
    -moz-opacity:0.6;
    -khtml-opacity: 0.6;
    opacity: 0.6; 
}
.radius, .someDiv {
    border-top-left-radius: 15px;
    border-top-right-radius: 5px;
    -moz-border-radius-topleft: 10px;
    -moz-border-radius-topright: 10px;    
}

您还可以将多个类应用于单个HTML元素(class属性采用空格分隔的列表)。

<div class="opacity radius">

这些方法中的任何一种都可以解决您的问题。

如果您使用描述了为什么要设置元素样式而不是应该如何设置样式的类名,可能会有所帮助。保留如何在样式表。


1
我不同意,但我需要评论,因为它不允许我将规则复制fieldset legendlabel.legend。我了解但后悔。
rishta '17

1
@rishta — Err…我在此答案的第一段中说过。
Quentin

您也可以像这样声明只有两个类的元素的规则集:.someDiv.other{/*style...*/}这样,只有两个类的元素都受到影响
Sirmyself

16

除非您使用某种扩展的CSS(例如SASS),否则您将无法这样做。但是,将这两个额外的类应用到上是非常合理的.someDiv

如果.someDiv是唯一的,我也将选择给它一个ID并使用该ID在CSS中引用它。


9

如果您愿意并能够使用一些jquery,则只需执行以下操作:

$('.someDiv').css([".radius", ".opacity"]);

如果您已经使用JavaScript处理了该页面,或者可以将其包含在<script>标记中。如果是这样,请将以上内容包装在文档准备功能中:

$(document).ready( function() {
  $('.someDiv').css([".radius", ".opacity"]);
}

我最近在更新wordpress插件时遇到了这个问题。它们已更改,在整个CSS中使用了许多“!important”指令。由于必须要在多个标签上声明!important,所以我不得不使用jquery来强制样式。


8

您可以使用@extend使用SASS预处理器轻松完成此操作。

someDiv {
    @extend .opacity;
    @extend .radius;
}

另外,您也可以使用JavaScript(jQuery):

$('someDiv').addClass('opacity radius')

最简单的当然是在HTML中添加多个类

<div class="opacity radius">

3

只需将类添加到您的html中

<div class="someDiv radius opacity"></div>

2

我昨天有这个问题。@Quentin的答案是可以的:

No, you cannot reference one rule-set from another.

但是我做了一个JavaScript函数来模拟CSS(例如.Net)中的继承:

    var inherit_array;
    var inherit;
    inherit_array = [];
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {
            if (cssRule_i.style != null) {
                inherit = cssRule_i.style.getPropertyValue("--inherits").trim();
            } else {
                inherit = "";
            }
            if (inherit != "") {
                inherit_array.push({ selector: cssRule_i.selectorText, inherit: inherit });
            }
        });
    });
    Array.from(document.styleSheets).forEach(function (styleSheet_i, index) {
        Array.from(styleSheet_i.cssRules).forEach(function (cssRule_i, index) {
            if (cssRule_i.selectorText != null) {
                inherit_array.forEach(function (inherit_i, index) {
                    if (cssRule_i.selectorText.split(", ").includesMember(inherit_i.inherit.split(", ")) == true) {
                        cssRule_i.selectorText = cssRule_i.selectorText + ", " + inherit_i.selector;
                    }
                });
            }
        });
    });

Array.prototype.includesMember = function (arr2) {
    var arr1;
    var includes;
    arr1 = this;
    includes = false;
    arr1.forEach(function (arr1_i, index) {
        if (arr2.includes(arr1_i) == true) {
            includes = true;
        }
    });
    return includes;
}

和等效的CSS:

.test {
    background-color: yellow;
}

.productBox, .imageBox {
    --inherits: .test;
    display: inline-block;
}

和等效的HTML:

<div class="imageBox"></div>

我测试了它并为我工作,即使规则位于不同的CSS文件中。

更新:我在此解决方案中发现了层次结构继承中的错误,并且即将解决该错误。


0

您可以使用var()函数。

var()CSS函数可用于插入自定义属性的值(有时称为“ CSS变量”),而不是其他属性值的任何部分。

例:

:root {
  --main-bg-color: yellow;
}

@media (prefers-color-scheme: dark) {
  :root {
    --main-bg-color: black;
  }
}

body {
  background-color: var(--main-bg-color);
}
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.