【问题标题】:Am I subclassing my CSS correctly?我是否正确地继承了我的 CSS?
【发布时间】:2012-03-02 01:07:58
【问题描述】:

我正在为我的网站制作一组按钮,我需要一些专业的见解。

为了减少 CSS 臃肿,我想将我的按钮子类化为不同的颜色,ex .button.blue 。

以后会不会出现以下问题? (假设我不只做一个 .blue 类) 我是否必须改用 .button.button-blue 之类的东西?

.button {
  display:inline-block;
  padding: 9px 18px;
  margin: 20px;
  text-decoration: none;
  font-family: Arial, Helvetica, sans-serif;
  font-size: 12px;
  font-weight: bold;
  text-align: center;
  background: #FFE150;
}
.button.blue {
  background: #49b8e7;
  border:1px solid #54abcf;
  border-bottom:1px solid #398fb4;
  color:#FFF
  text-shadow: 0 1px 0 rgba(255,255,255, 0.5);
}
.header{
  height: 50px;
}
.header.blue {
  background: blue;
  color: #fff;
}

【问题讨论】:

  • CSS 中没有子类化 的概念。你可以添加额外的类。

标签: css subclassing css-cascade


【解决方案1】:

组合应用您想要主题的颜色的类。

HTML:

<input type="text" class="text-field-required default" .../>
<select class="autocomplete-drop-down blue">...</select>
<a href="#" class="button-link green" .../>

CSS:

.text-field-required {
    //component css theme without colors
}
.default {
    //default color css theme for any component
}
.blue {
    //blue css theme for any component
}
.green {
    //green css theme for any component
}

【讨论】:

    【解决方案2】:

    好像button.blue 就够了。

    两者之间的唯一区别是使用&lt;button class="button blue"&gt;&lt;button class="button button-blue"&gt;

    你甚至不需要用蓝色复制这幅画......你可以这样做:

    .button
    {
    // button style
    }
    
    .header
    {
    // header style
    }
    
    .blue
    {
       background: blue; 
       color: #fff; 
    }
    

    当然,如果您将蓝色类添加到它们中的每一个。 (&lt;div class="header blue"&gt;and&lt;button class="button blue"&gt;)

    【讨论】:

      【解决方案3】:

      假设您希望它们像这样工作,那么您拥有的多类将正常工作:

      <div class="button blue">
      Will use .button and .button.blue
      </div>
      
      <div class="button">
      Will only use .button
      </div>
      
      <div class="header blue">
      Will  use .header and .header.blue
      </div>
      
      <div class="header">
      Will only use .header
      </div>
      
      <div class="blue">
      Will use neither of the .blue declarations because it doesn't contain header or button.
      </div>
      

      【讨论】:

      • 谢谢,这真的让我思考......我上面的代码的真正缺点是,如果另一个开发人员创建一个 .blue 类,它将破坏整个站点。其中 .btn-blue 将仅包含在该“模块”中。
      • 没错。如果创建一个独立的 .blue 肯定会导致一些问题。
      【解决方案4】:

      像 .button.blue 这样的选择器实际上选择了一个同时具有“blue”和“button”作为类的元素,而不是一个名为 .button.blue 的类。见http://www.w3.org/TR/CSS21/selector.html#class-html

      您可以使用您列出的 .button.blue 样式规则,但您需要重新排列您的 HTML 以便获得类似 &lt;button type="button" class="button blue"/&gt; 的内容。但是,您实际上并不需要一个按钮类,因为它是一个按钮(或&lt;input type="submit"&gt; 等)足以在您的选择器中使用。您可以编写一个简单的 CSS 规则 button.blue, input[type=submit].blue{}

      【讨论】:

      • 酷,我没想过像那样添加输入[type=submit] =)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-08-13
      • 1970-01-01
      • 2013-11-30
      • 2011-09-06
      • 1970-01-01
      相关资源
      最近更新 更多