如何创建CSS类Union?

时间:2010-11-03 15:32:36

标签: css stylesheet union

我有一个div,它将CSS类联合起来:

    <div id="tp" class="ui-hidden-on-load ui-tablepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible">
        ...
    </div>

如何创建一个CSS样式,我可以将所有这些类组合成一个具有谨慎名称的单个类?

示例:

<div class="myCustomClass">
...
<div>

我的自定义类是所有组合类的交集?我似乎无法找到一个如何做到的例子或好的解释。

提前感谢您阅读我的问题!

3 个答案:

答案 0 :(得分:5)

在CSS中无法实现的AFAIK。您可以将规则提供给多个选择器:

.one, .two, .three { color:red; }

或者手动将泛型类添加到每个HTML元素。

如果您想定位具有某些类的元素,您可以执行.one.two.three {}

答案 1 :(得分:1)

您可以尝试使用LESS或SCSS之类的东西来实现这些类in mixins的可重用元素。请注意,您不必在ruby应用程序中使用其中任何一个;在PHP,JavaScript和.NET以及SCSS中有多个LESS端口可以独立运行(但需要运行ruby)

答案 2 :(得分:0)

我认为你正在向后看问题。如果所有这些类都具有与之关联的相同CSS规则,那么您应该只在样式表中组合这些规则。但是我想你最终会发现,正如Jason McCreary评论的那样,这将导致灵活性降低和工作量增加。

您的示例中列出的类很可能来自某个UI框架,DOM树下面的元素将根据它们是否是具有特定类的元素的后代来进行样式化,即。像这样的规则:

.ui-tablepicker td a {/* some style */}

但是还会有其他规则:

.ui-widget-content a {/*some other style*/}

如果你想要组合这些类名,你最终会得到类似的东西:

.myCustomClass1 a {/* Replaces case where only .ui-tablepicker parent exists */}
.myCustomClass1 td a {/* Replaces case where only .ui-tablepicker parent exists */}
.myCustomClass2 a {/* Replaces case where only .ui-widget-content parent exists */}
.myCustomClass2 td a {/* Replaces case where only .ui-widget-content parent exists */}
.myCustomClass3 a {/* Replaces case where both exist */}
.myCustomClass3 td a {/* Replaces case where both exist */}

这是类名的分离,使样式表易于管理。

如果反复输入所有这些类,那么请使用变量将它们保存在页面生成代码中,例如:

<?
$myCustomClass = "ui-hidden-on-load ui-tablepicker ui-widget ui-widget-content ui-helper-clearfix ui-corner-all ui-helper-hidden-accessible";
?>
<div id="tp1" class="<? echo $myCustomClass; ?>">
    ...
<div id="tp2" class="<? echo $myCustomClass; ?>">