需要有关此css选择器的更多见解

时间:2012-02-10 13:12:29

标签: css css-selectors

<head>   
    <style>
        .thisOne{ background: red;}
        div[class*="thisTwo"] { background: green}
    </style>
</head>
<body>
    <div class="thisOne">
        <p id="hello">Hello World</p>
    </div>
    <div class="thisTwo">
        <p id="hello">Hello World</p>
    </div> 
</body>

我想知道这种选择方式有何不同:

  1. .thisOne{ background: red;}
  2. div[class*="thisTwo"] { background: green}
  3. 他们做同样的工作,对吧?为什么双选择器会更先进?

2 个答案:

答案 0 :(得分:2)

实际上,他们没有做同样的事情。与div.thisTwo完全相同的属性选择器是div[class~="thisTwo"]。请注意使用~而不是*。更不用说您的.thisOne选择器也缺少前面的div

div[class*="thisTwo"]选择其div属性包含字符串class的任何thisTwo,但它不会考虑将此字符串分隔的任何空格来自其他课程。它只是在属性值的任何地方查找字符串。

这意味着它将匹配以下div.thisTwo无法匹配的元素,因为它只有一个类 thisOne-thisTwo,其中包含字符串{{1} },而不是两个单独的类 thisTwothisOne

thisTwo

答案 1 :(得分:1)

不,不。第一个将选择类名为thisOne的任何元素。第二个将选择其类包含术语div的任何thisTwo