多个css类的单个标识符

时间:2017-12-08 07:36:33

标签: css css-selectors

我经常将css类捆绑在一起,如下所示:

<div class="row z-depth-2 gradient-background">
... Blah
</div>

我有三个类:row z-depth-2 gradient-background在200多个地方一起使用。我怎样才能将这三个一起引入单一课程?

我不介意CSS或SASS。另一个问题是rowz-depth-2materialize.css中定义,我不想触摸。所以我不能像SASS一样简单地在SASS中扩展这些类:

.input-group {
    @extend .row, .z-depth-2, .gradient-background
}

所以我希望能够做到这样的事情:

<div class="input-group">
    ... Blah
</div>

1 个答案:

答案 0 :(得分:1)

为什么不简单地将这三个类用作一个选择器,如.row.z-depth-2.gradient-background。它将允许您选择具有这3个类的元素(当然它可以有更多):

&#13;
&#13;
div {
  margin:10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {/* pay attention as there is no spaces between the classes*/
  background: red;
}
&#13;
<div class="row z-depth-2 gradient-background">
<!-- Select this one -->
</div>
<div class="row gradient-background">

</div>

<div class="row z-depth-2">

</div>

<div class="row gradient-background z-depth-2 more-class">
<!-- Select this one -->
</div>
&#13;
&#13;
&#13;

有用链接以获取更多详细信息:

https://css-tricks.com/multiple-class-id-selectors/

Using two CSS classes on one element

<强>更新

如果你想使用一个稍后将被这3个替换的新类,你可以使用一个小的jQuery脚本来做你需要的,如下所示:

&#13;
&#13;
//select all element with class input-group
$('.input-group').each(function() {
  $(this).removeClass('input-group'); //remove input-group
  $(this).addClass('row z-depth-2 gradient-background'); //add the other classes
})
&#13;
div {
  margin: 10px;
  height: 20px;
  background: blue;
}

.row.z-depth-2.gradient-background {
  /* pay attention as there is no spaces between the classes*/
  background: red;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="input-group">

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

</div>
&#13;
&#13;
&#13;