What is css “[class*=my-class] .my-subclass” doing

2019-02-22 08:41发布

问题:

I inherited some css and I have searched everywhere online to understand what is being expressed by a block of css that looks like:

 [class*=wrapper] .logo {
                padding-top: 32px !important;
            }

What is the asterisk and square brackets doing?

It is hard to search for [ and * on google... Sorry if the question is dumb.

回答1:

It selects an element with class logo that has an ancestor that has wrapper somewhere in its class attribute. For example note that the class burgerwrapper also leads to the element being selected below.

[class*=wrapper] .logo {
  color: #f99;
}
<div class="logo">Not selected</div>

<div class="wrapper">
  <div class="logo">
    Selected
  </div>
</div>

<div class="burgerwrapper">
  <div class="logo">
    Selected
  </div>
</div>

See http://css-tricks.com/attribute-selectors/ for some background information on attribute selectors.



回答2:

what square brackets doing

Attribute selectors

CSS 2.1 allows authors to specify rules that match elements which have certain attributes defined in the source document.

Attribute selectors w3

What is the asterisk

Substring matching attribute selectors

[att*=val] Represents an element with the att attribute whose value contains at least one instance of the substring "val". If "val" is the empty string then the selector does not represent anything.

Substring matching attribute selectors

To sum it up in you example:

[class*=wrapper] .logo {
  color: red;
}
<div class="wrapper">
  <div>not this</div>
  <div class="logo">this</div>
  <div class="logo">this</div>
</div>
<div>
  <div>not this</div>
  <div class="logo">not this</div>
  <div>not this</div>
</div>

Select child elements with class .logo that their parent element has attribute class with value wrapper appears somewhere in that attribute.