【问题标题】:How to simplify my CSS stylesheet?如何简化我的 CSS 样式表?
【发布时间】:2013-08-19 23:30:19
【问题描述】:

我正在尝试在 CSS 表中简化我的 CSS 选择器

我有类似的东西

.table_test .div, .table_name .div, .table_company .div{
    color:black;
}


.table_test .div table input, .table_name .div table input{
    color:red;
}

我的 html 类似于

<div class='table_test'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>

<div class='table_name'>
  <div class='div'>......
  <table>
   <tr>
    <td><input>...</td> 
   </tr>
  </table>
</div>

我觉得有很多选择器聚集在一起,想知道是否有办法让它变得更简单。感谢您的帮助!

【问题讨论】:

    标签: html css


    【解决方案1】:

    一些事情:

    不要使用通用类名,例如 div。已经有一个名为div 的元素元素。如果您想基于嵌套来定位它,请使用 CSS。

    .table_name > div {} /* or .table_name div */
    

    不是……

    .table_name .div {}
    

    使用特定的选择器。您是否有理由需要通过table_name .div table input?为什么不通过给它一个类来专门针对输入?

    <input class="my_input">
    

    然后:

    .my_input {
      color: red;
    }
    

    最后,由你决定使用什么样式,但大多数人倾向于在 html 属性周围使用双引号。例如:

    &lt;div class="table_name"&gt; 而不是&lt;div class='table_name'&gt;

    【讨论】:

    • 双引号还是单引号,没关系。
    • 我想这是真的,但是当您需要在属性中使用单引号时,它确实会有所不同;例如,作为标题文本的一部分。
    【解决方案2】:

    您可以创建一个相同样式的表共享的类名

    CSS

    .similar-table .div{
        color:black;
    }
    
    
    .similar-table input{
        color:red;
    }
    

    HTML

    <div class='table_test similar-table'>
      <div class='div'>......
      <table>
       <tr>
        <td><input>...</td> 
       </tr>
      </table>
    </div>
    
    <div class='table_name similar-table'>
      <div class='div'>......
      <table>
       <tr>
        <td><input>...</td> 
       </tr>
      </table>
    </div>
    

    【讨论】:

      【解决方案3】:

      CSS:

      .red{
        color:red;
      }
      .black{
        color:black;
      } 
      

      HTML:

      <div class='table_test'>
       <div class='div'>......
        <table>
         <tr>
          <td><input class="black">...</td> 
         </tr>
       </table>
      </div>
      
      <div class='table_name'>
       <div class='div'>......
        <table>
         <tr>
          <td><input class="red">...</td> 
         </tr>
        </table>
      </div>
      

      最好的部分?这个 CSS 可以工作 wherever you need it to

      【讨论】:

      • redfloat-left 这样的类名有点违背了CSS 的意义。我肯定见过有人做.blue-text {color:black !important} 之类的废话。
      • 可能是这样,但这些是示例类名,不适合实际使用。我认为 OP 的 .div 是一样的。至少我希望是……
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 2019-07-07
      • 2010-10-12
      相关资源
      最近更新 更多