29 - CSS Attribute Selectors

Attribute selectors are used for selecting elements based on a particular attribute. It also selects elements by exactly or partially matching an attribute value.

This feature was added in CSS2 and few more additions were made to CSS3 version.

Attribute selectors are surrounded with square brackets.

Types of Attribute Selectors

[at_name]

This selector selects the elements that has an attribute with name “at_name”

[at_name=value]

This selector selects the element whose attribute name is “at_name” and value exactly same as “value”.

[at_name~=value]

This selector selects an element whose attribute name is “at_name” and any of the attribute values as “value”.

[at_name|=value]

Selects an attribute with name “at_name” and whose value is exactly “value” or begins with “value”

[at_name^=value]

Selects the elements whose attribute name is “at_name “and whose attribute value begins with “value”

[at_name$=value]

Selects the elements whose attribute name is “at_name “and whose attribute value ends with “value”

[at_name*=value]

Selects the elements whose attribute name is “at_name “and whose attribute value has at least one occurrence of “value” in the attribute value.

An Example program

<html>
   <head>
      <style>
         a[target]{
         font-size:16pt;
         color:Green;
         }
         [class=para]
         {font-weight:bold;}
         [font~=serif]{
         background:green;}
         [class*="te"] {
         background: yellow;
         }
      </style>
   </head>
   <body>
      <a href="www.google.com" target="_blank"> I am a link!</a>
      <div class="para"> I am in div</div>
      <div font="serif  verdana"> I am a div with 200 width</div>
      <div class="tele"> Iam in another div</div>
   </body>
</html>

The output of the above program would be

   

Like us on Facebook