CSS attribute selectors

Attribute selectors select only those elements that follow the rules set by teh attribute selectors. The element must have the same attribute that matches against the respective attribute selectors.

The following is the list of attribute selectors.

1. [attrib]

This attribute selector represents an element that has the exactly the same attribute as in the [attribute] selector. It does't matter what is the value of this attribute.

Example

<style>
input[type]
{
  width:100px;
}
</style>
Try </>

It selects all of the <input> elements that have type attribute. It does not matter whatever may be the value of this attribute.

2. [attrib=val]

It selects those elements that have exactly the same attrib and val as in the [attribute=value] selector.

Example

<style>
div[title="warning"]
{
 background-color:rgba(255,0,0,0.5);
 padding:5px;
}
</style>
Try </>

This element selects <div> element that has title attribute and warning value.

Remember that the attribute and value of element must match with the attribute and value of the attribute selector.

3. [attrrib~=val]

In this case, it selects the element with the attrib attribute that has more than one values separated by spaces. And one of those values must match with the val.

Example

<style>
a[rel~="next"]
{
 background-color:lightblue;
 color:green;
}
</style>
Try </>

For example, we have <a> element that has rel attribute. And the values of rel attribute are separated by spaces such as "next nextone nexttwo". But, only one of these value matches the value of [rel~=next].

4. [attrib|=val]

It represents an element with attrib attribute and value should be exactly val or val followed by a hyphen (-).

Example

<style>
a[hreflang|="en-US"]
{
 background-color:lightblue;
 color:green;
}
</style>
Try </>

It represents <a> element with hreflang attribute and en keyword or en followed by a hyphen (-).

5. [attrib^=val]

^ containing attribute selector selects an element with attrib attribute and value should begin with val.

Example

<style>
img[type^="image/"]
{
 border:5px solid black;
}
</style>
Try </>

It allows to select only <img> element with type attribue and value should start from the image/.

6. [attrib$=val]

$ containing attribute selector selects an element with attrib attribute and should end with the val

Example

<style>
img[type$="png"]
{
 opacity:0.5;
 border:2px solid black;
}
</style>
Try </>

This example selects <img> element with type attribute and the value should end with png.

7. [attrib*=val]

* containing attribute selector selects element with attrib attribute and the value of this attribute should contain val substring.

Example

<style>
p[class*="sign"]
{
 font-size:25px;
 font-family:papyrus;
}
</style>
Try </>

It selects <p> element with class attribute and the value of this attribute should contain sign as substring.



Was this article helpful?

 

Email:

Message: