Share

One of the great things about CSS3 is the ability to remove more styling from the html and put the styling in the css file which results in cleaner html.

 

CSS3 introduces three new selectors that can match strings against an attribute value at the beginning, the end, or anywhere within the value. This allows us to style different href links with icons relating to the type of link.

 

Before I show you the new way of styling links, I will first show you the old way. 

 

Tried and True

 

Suppose we want to style pdf links. We would use the following:

 

Then in the css, we would style all links that link to pdf documents with the pdf class.

a.pdf {
     background: url(../img/pdf.png) no-repeat 0 0;
     padding-left:35px;
}

 

The key problem here is we would style all links that link to pdf documents.

 

If you are a web company letting users adding content, then they would have to add the proper pdf class to the link. If you like to have different icons for different links such as mailto: links, external links and ftp links, the users would have to remember all the different classes that need to be added. Not good. The solution: CSS3 attribute selectors.

 

Introducing CSS3 Attribute Selectors

 

CSS3 Attribute Selectors allow the ability to style elements (like tags) based on an attribute (like the href attribute)

 

There are three additional attribute selectors are provided for matching substrings in the value of an attribute:

E[att^="string"] {property: value;}
E[att$="string"] {property: value;}
E[att*="string"] {property: value;}

 

The first represents an element with the att attribute whose value begins with the prefix “string”.
 

The second represents an element with the att attribute whose value ends with the suffix “string”.
 

The third represents an element with the att attribute whose value contains at least one instance of the substring “string”.

 

Like most new CSS3 items, it's easier to show then explain, so below are some examples with the code used to produce them. Note that the links have no classes on them.

The css code

a[href^="mailto:"] {
     display:block;
     background:url(../img/mailto.png) no-repeat 0 0;
     padding-left: 35px;
     height:30px;
}
a[href^="ftp://"] {
     display:block;
     background:url(../img/ftp.png) no-repeat 0 0;
     padding-left: 35px;
     height:30px;
}
a[href$=".pdf"] {
     display:block;
     background:url(../img/pdf.png) no-repeat 0 0;
     padding-left: 35px;
     height:30px;
}
a[href$=".xml"] {
     display:block;
     background:url(../img/rss.png) no-repeat 0 0;
     padding-left: 35px;
     height:30px;
}

Related Chatter