Wildcard selector is used to select multiple elements simultaneously. It selects similar type of class name or attribute and use CSS property. * wildcard also known as containing wildcard.
Wildcard selectors allow you to select multiple matching elements. In CSS, three wildcard selectors exist i.e. $, ^, and * The * wildcard is known as the containing wildcard since it selects elements containing the set value. With the ^ wildcard, you get to select elements whose attribute value starts with the set ...
Your answerAsterisk (*): It is used for replacing 1 or more characters from a selector attribute.
To select elements with a specific class, write a period (.) character, followed by the name of the class. You can also specify that only specific HTML elements should be affected by a class. To do this, start with the element name, then write the period (.)
In CSS you can use the attribute selector with ^
:
div[class^="div-"]
==> Selects all div
with a class
attribute value starting with "div-"
Example:
div {
height: 20px;
margin-bottom: 5px;
border: 1px solid black;
}
div[class^="div-"] {
border-color: red;
}
<div class="div-one"></div>
<div class="div-two"></div>
<div class="other"></div>
<div class="div-three"></div>
As @FreePender says, if the CSS class isn't the one in the attribute's value, it doesn't work. Another solution is to use the attribute selector with *
:
div[class*="div-"]
==> Selects all div
with a class
attribute value containing "div-".
This way it would also match a CSS class named nodiv-one
for example, but it's not something that happens normally.
div {
height: 20px;
margin-bottom: 5px;
border: 1px solid black;
}
div[class*="div-"] {
border-color: red;
}
<div class="div-one"></div>
<div class="div-two"></div>
<div class="other"></div>
<div class="myclass div-three"></div>
Small point but I noticed that when nesting this rule in Sass, you need to put the ampersand right against the opening square bracket.
This doesn't work:
.zoomed {
& [class*=" aspect-"] {
margin-bottom: $spacer * 4.0;
}
}
But this does:
.zoomed {
&[class*=" aspect-"] {
margin-bottom: $spacer * 4.0;
}
}
Note the position of the ampersand.
The accepted answer is cool in theory, but in the latest chrome as of today:
For the CSS rule:
[class^="div-"]
the markup
class="div-something other-class"
matches, whereas:
class="other-class div-something"
does not match
¯\_(ツ)_/¯
You may use this method to do. Create a mixin:
@mixin myDIV($name, $color, $color-hover) {
.div-#{$name} {
a {
color: #{$color};
&:focus, &:hover {
color: #{$color-hover};
}
}
}
}
Usage:
@include myDIV('one', $blue, $blue-hover);
@include myDIV('two', $green, $green-hover);
@include myDIV('three', $red, $red-hover);
You may change the variables ($blue) and css properties to suits your styles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With