使用一个类而不是几个

时间:2017-06-15 17:32:58

标签: css

我经常使用几个类的组合:

<a href="something" class="btn btn-default btn-block btn-lg mt20">something</a>

如果有办法我可以简化?例如

<a href="something" class="btn-my">something</a>

其中.btn-my将是.btn .btn-default .btn-block .btn-lg .mt20的组合 我怎么能在css文件中做到这一点?是否有更简单的东西像

.btn-my{.btn .btn-default .btn-block .btn-lg .mt20} 

3 个答案:

答案 0 :(得分:0)

例如:

// spread out css
.class1 {
  background: blue;
}

.class2 {
  color: white;
}

// consolidated css
.myConsolidatedClass {
  background: blue;
  color: white;
}

就组合类而言,css默认不支持。我会考虑使用scss,您可以使用modules / w @include

这是你的代码使用scss看起来的样子:

@mixin background($color){
  background: $color;
}

@mixin color($color){
  color: $color;
}

.class1 {
  @include background(blue);
}

.class2 {
  @include color(white);
}

.myConsolidatedClass {
  @include background(blue);
  @include color(white);
}

请注意,您可以在mixins中添加任意数量的属性,为了简单起见,我只做了一个。

答案 1 :(得分:0)

您可以将自定义类添加到要在CSS文件中共享的选择器中。

.btn, .btn-my {
  color: red;
}
.btn-default, .btn-my {
  padding: 3em;
}
.btn-block, .btn-my {
  display: block;
}
.btn-lg, .btn-my {
  width: 50vw;
}
.mt20, .btn-my {
  background: black;
}
<button class="btn">btn</button>
<button class="btn-default">btn</button>
<button class="btn-block">btn</button>
<button class="btn-lg">btn</button>
<button class="mt20">btn</button>

<button class="btn btn-default btn-block btn-lg mt20">btn</button>
<button class="btn-my">btn-my</button>

答案 2 :(得分:0)

您可以将这些规则组合成一个新的类,如下所示:

&#13;
&#13;
.btn-my {
    display: block;
    width: 100%;
    padding: 10px 16px;
    margin-bottom: 0;
    margin-top: 20px;
    font-weight: 400;
    font-size: 18px;
    line-height: 1.3333333;
    text-align: center;
    color: #333;
    background-color: #fff;
    white-space: nowrap;
    vertical-align: middle;
    -ms-touch-action: manipulation;
    touch-action: manipulation;
    cursor: pointer;
    -webkit-user-select: none;
    -moz-user-select: none;
    -ms-user-select: none;
    user-select: none;
    background-image: none;
    border: 1px solid #ccc;
    border-radius: 6px;
}
  .btn-my:hover {
      color: #333;
      background-color: #e6e6e6;
      border-color: #adadad;
  }
&#13;
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<a href="something" class="btn-my">something</a>
&#13;
&#13;
&#13;

相关问题