css3 attribute selectors

css3 attribute selectors

In previous article in this series we looked in to css selectors. HTML elements can have attributes and in CSS3 we can use these attributes to select elements.  The [attribute] in an  element is used to select elements with a specific element.

So

element[attribute]

Select element containing the named attribute.

img[alt]

The above attribute is used to select img elements with an alt tag  like

<img src="mage.jpg" alt = "alt text for an image" />

Consider the expression below

form  [type]

or 
form input[type]

<input type="text" />

The above expression will match all the form on the document having descendants with type attribute.

E[attr]

This expression will match any element E that has attribute attr and the expression

E[attr="val"]

will match all E elements with attribute attr with the exact, case sensitive, if attribute is case sensitive , vaue val.

E[attr|=val]

The above expression will match element E that is exactly equal to val or starts with val followed by a dash. like val or val-

Example

p[lang|="en"]{
   /* 
   <p lang= "en-us" /> <p lang="en-uk" />
   */
}

Consider an other expression

E[attr~=val]

Element E whose attribute attr has within its value the space separated full word val. 

Example

a[title~=more] {
 /* 
  <a title = "want more info about this?" />

*/
}

The above expression will match above hyper link because it has word more with a space.

but it will not match below expression.

a[title~=ant] {
 /* 
  <a title = "want more info about this?" />
*/
}

Here word ant is present in want but it will not match because there is no space before ant.

 

E[attr^=val]

Matches element E whose attribute attr starts with value val.

Examples:

a[href^=mailto]{ background-image: url(emilicon.gif); }

a[href^=http]:after{ content: " ( " attr(href) ")" ; }

Consider another expression.

E[attr$=val]

Matches element E whose attribute attr ends in value val.

Examples

a[href$=pdf] { background-image: url(pdficon.gif); }

a[href$=pdf]:after{ content: " ( "PDF ")" ; }

Consider following expression.

E[attr*=val]

Matches element E whose attribute attr matches  val anywhere within the attribute. Its behavior is same as E[attr~=val] , except the val can  be part of word.

Examples

a[href$=pdf] { background-image: url(pdficon.gif); }

a[href$=pdf]:after{ content: " ("PDF ")" ; }

Multiple attributes can also work like a[title][href]

So thats it for this article. In out next article we will look into Psuedo classes in CSS3.

No Responses