What is this CSS selector? [class*="span"]
I saw this selector in Twitter Bootstrap:
.show-grid [class*="span"] {
background-color: #eee;
text-align: center;
border-radius: 3px;
min-height: 30px;
line-height: 30px;
}
Does anyone know what this technique is called and what it does?
It's an attribute wildcard selector. In the sample you've given, it looks for any child element under .show-grid
that has a class that CONTAINS span
.
So would select the <strong>
element in this example:
<div class="show-grid">
<strong class="span6">Blah blah</strong>
</div>
You can also do searches for 'begins with...'
div[class^="something"] { }
which would work on something like this:-
<div class="something-else-class"></div>
and 'ends with...'
div[class$="something"] { }
which would work on
<div class="you-are-something"></div>
Good references
- CSS3 Attribute Selectors: Substring Matching
- The 30 CSS Selectors you Must Memorize
- W3C CSS3 Selectors
.show-grid [class*="span"]
It's a CSS selector that selects all elements with the class show-grid that has a child element whose class contains the name span.
The Following:
.show-grid [class*="span"] {
means that all child elements of '.show-grid' with a class that CONTAINS the word 'span' in it will acquire those CSS properties.
<div class="show-grid">
<div class="span">.span</div>
<div class="span6">span6</div>
<div class="attention-span">attention</div>
<div class="spanish">spanish</div>
<div class="mariospan">mariospan</div>
<div class="espanol">espanol</div>
<div>
<div class="span">.span</div>
</div>
<p class="span">span</p>
<span class="span">I do GET HIT</span>
<span>I DO NOT GET HIT since I need a class of 'span'</span>
</div>
<div class="span">I DO NOT GET HIT since I'm outside of .show-grid</span>
All of the elements get hit except for the <span>
by itself.
In Regards to Bootstrap:
-
span6
: this was Bootstrap 2's scaffolding technique which divided a section into a horizontal grid, based on parts of 12. Thusspan6
would have a width of 50%. - In the current day implementation of Bootstrap (v.3 and v.4), you now use the
.col-*
classes (e.g.col-sm-6
), which also specifies a media breakpoint to handle responsiveness when the window shrinks below a certain size. Check Bootstrap 4.1 and Bootstrap 3.3.7 for more documentation. I would recommend going with a later Bootstrap nowadays
It selects all elements where the class name contains the string "span"
somewhere. There's also ^=
for the beginning of a string, and $=
for the end of a string. Here's a good reference for some CSS selectors.
I'm only familiar with the bootstrap classes spanX
where X is an integer, but if there were other selectors that ended in span
, it would also fall under these rules.
It just helps to apply blanket CSS rules.