We’ve previously talked about ID and class selectors. There is another type of selector which is kind of similar to them and this is the attribute selector. With an attribute selector we can match elements with specific attributes or attribute values without adding any ID or classes to the element.
For example, you could target a text input filed as follows:
input[type="text"] {
padding: 10px;
}
This will add 10px padding to all text inout field in your HTML document. Here is a few more examples.
Let’s say you have divs with the class of “container” in your document like this:
<div class="container">
this is a text inside a container
</div>
You could target this with attribute selector like this:
div[class~="container"] {
color: red;
}
This will select all elements that have class attributes containing the value “container”.
Let’s say you want to target an element whose classname contains a specific word. So not the entire classname, just part of it.
You could have an HTML like this:
<div class="first-section">
this is a text inside the first section
</div>
And you could select it like this:
div[class*="first"] {
color: green;
}
You can achieve the same result by replacing the asterisk symbol with a pipe symbol
div[class|="first"] {
color: green;
}
In this case the value can be exactly the specified value (first), or the specified value followed by a hyphen. In this example “first” is followed by a hyphen.
Again we can achieve something similar by using the carrot symbol:
div[class^="first"] {
color: green;
}
Here we select the classes whose value starts with “first”.
We can also select elements where the attribute value ends with a specific word or value
div[class$="section"] {
color: green;
}
External resources:
Leave a reply
You must be logged in to post a comment.