【问题标题】:Changing the order of comma-separated selectors breaks styling更改以逗号分隔的选择器的顺序会破坏样式
【发布时间】:2017-03-09 02:58:11
【问题描述】:

如果我更改子选择器中元素的顺序,它会影响类之外的元素。

普通 HTML:

<input type='text'>
<hr>
<table class="mytable">
  <tbody> 
    <tr><td><input type='text'></td></tr>
    <tr><td><input type='text'></td></tr>
    <tr><td><input type='text'></td></tr>
  </tbody>
</table>

此 CSS 有效 (jsfiddle):

input {
  margin: 0 0 2em;
}
table.mytable input,select,a {
  margin: 0;
}

以下 CSS 只需将 &lt;select&gt; 放在元素的子列表 (jsfiddle) 的首位,就会导致表格前的第一个输入丢失其边距。也就是 mytable 类在不应该被激活(选中)的第一个输入框。

input {
  margin: 0 0 2em;
}
table.mytable select,input,a {
  margin: 0;
}

我在 Chrome 和 Firefox 中都对此进行了测试,它们的行为方式相同。那么这是一个错误吗?或者有人可以解释我缺少什么吗?

【问题讨论】:

    标签: html css css-selectors


    【解决方案1】:

    第一个选择器:

    table.mytable input, select, a
    

    针对以下元素:

    • table.mytable 后代的输入
    • 所有select元素
    • 所有锚元素

    table.mytable input 使用descendant combinator(空格)来构造表/输入关系。它仅将margin: 0 应用于那些特定的输入。

    您的第二个选择器:

    table.mytable select, input, a 
    

    将margin: 0 应用于这些元素:

    • select 是 table.mytable 后代的元素
    • 所有input元素
    • 所有锚元素

    因此,您的第一个选择器针对特定的一组输入,而第二个选择器针对所有个输入。

    在first example 中,第一个输入规则针对所有输入。但是由于higher specificity,第二个输入规则会覆盖第一个规则。第一条规则最终匹配所有输入,第二条规则所针对的除外。

    在second example 中,第一个和第二个输入规则针对同一组(所有输入)并且在特异性方面具有相同的权重。第二条规则获胜,因为it is processed later in the cascade。因为两个规则都针对同一个组,所以第一个规则被覆盖,从而导致您遇到的问题。

    要仅针对表中的输入,请尝试以下操作:

    table.mytable select, 
    table.mytable input,
    a 
    

    【讨论】:

      【解决方案2】:

      您的 CSS 编写方式并不像您希望的那样在“子集”中工作。

      通过先放置 select,您现在无意中删除了所有输入的边距。

      如果我把它拆开,你现在的样子会是这样的:

      input {
          margin: 0 0 2em;
      }
      
      table.mytable input {
          margin: 0;
      }
      
      select {
          margin: 0;
      }
      
      a {
          margin: 0;
      }
      

      要让它按照您想要的方式工作,您需要在每个逗号后包含 table.mytable 以及您想要的每个“子集”。

      input {
           margin: 0 0 2em;
      }
      
      table.mytable select,
      table.mytable input,
      table.mytable a {
          margin: 0;
      }
      

      【讨论】:

        【解决方案3】:

        试试这个。

        input {
          margin: 0 0 2em;
        }
        table.mytable select, table.mytable input, table.mytable a {
          margin: 0;
        }
        <input type='text'>
        <hr>
        <table class="mytable">
          <tbody> 
            <tr><td><input type='text'></td></tr>
            <tr><td><input type='text'></td></tr>
            <tr><td><input type='text'></td></tr>
          </tbody>
        </table>

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2017-05-26
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-08-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多