CSS attribute selectors

      No Comments on CSS attribute selectors

CSS attribute selectors are used to style the elements that have a particular property or attribute.

CSS attribute selectors

The [attribute] selector is used to select elements with a specified attribute.
For example:

img[alt]
{
  padding:5px;
  border:solid 1px orange;
}

Result:


I do not have alt attribute

CSS attribute selecotrs
I have alt attribute


CSS [attribute=”value”] Selector

CSS attribute selectors can also be used to style the elements that have a particular value for a property or attribute.
For example:

<style>
a[href="http://scanfcode.com/css-attribute-selectors"]
{
  color:red;
}
</style>
<a href='http://scanfcode.com/css-attribute-selectors'>Link with value=http://scanfcode.com/css-attribute-selectors</a>
<a href='http://scanfcode.com/'>Link with value not equal to http://scanfcode.com/css-attribute-selectors</a>

Result:

CSS [attribute^=”value”] Selector

The [attribute^="value"] selector is used to select elements whose attribute value begins with a specified value.
For example:

<style>
[class^="oi"] {
    background: yellow;
}
</style>
<div class='oiltest'>Hi</div>

Result:

Hi

CSS [attribute$=”value”] Selector

The [attribute$="value"] selector is used to select elements whose attribute value ends with a specified value.
For example:

<style>
[class$="y1"] {
    background: pink;
}
</style>
<div class='classy1'>Hi</div>

Result:

Hi

CSS [attribute*=”value”] Selector

The [attribute*="value"] selector is used to select elements whose attribute value contains a specified value.

<style>
[class*="oi1"] {
    background:lightblue;
}
</style>
<div class='classoi1'>Hi</div>
<div class='class2'>Hi</div>
<div class='oi1t-class'>Hi</div>
<div class='class1'>Hi</div>
<div class='class_oi1test'>Hi</div>

Result:

Hi
Hi
Hi
Hi
Hi

Leave a Reply

Your email address will not be published. Required fields are marked *