CSS: A tribute to selectors

I wanted to learn more about CSS attribute selectors.

Two things happened on Friday which prompted me to talk about CSS attribute selectors. The first was an email plopping into my inbox,

Hi Andy,

I was just scanning through your CSS and noticed the following line of code:
div[id=”content-sub”] p span {
display : block;
background : url(../images/x.png) no-repeat; }

I’m basically wondering what the [ ] are for? I’ve never seen it used anywhere and couldn’t find any information about it on Google.

Thanks, Alex.

The second was working on a new web site with the mighty Brothercake. Scanning through the CSS he had written, like Alex, I was intrigued by,
*[id^=”content-supp”]#content-supp:lang(en) {
left : 34.6%;
margin-left : 0; }

So, wanting to find out about these types of selectors I did a bit of reading around, but many of the explanations were a tad complicated. So I made some experiments of my own and thought I’d share them. Now I’m no CSS God like Brothercake, so please forgive my rather simplistic explanations.

Before we start, if you’re reading this with Internet Explorer, go and amuse yourself for a few minutes, as attribute selectors won’t work in the world’s most popular (sic) browser. Still here? Phew, let’s crack on.
Attribute selectors

Attribute selectors allow you to target an element based upon its ‘attribute’. Here are some examples, (attributes in bold).
<a href=”” title=”” ></a>
<q cite=”” ></q>
<img src=”” alt=”” />
<div id=”” ></div >
<p ></p>

The first example targets any element which has a specific attribute, for example all anchors which have a title attribute. In this example, anchors with titles attributes will display a dotted bottom border. (1)
<a href=”/” title=”Andy Clarke” >Malarkey</a>
a[title] { border-bottom : 1px dotted #900 }

(2) Now for greater specivity, we can also target only anchors where the title attribute contains only the word ‘Malarkey’,
<a href=”/” title=”Malarkey” >Malarkey</a>
a[title=”Malarkey”] { border-bottom : 1px dotted #900; }

(3) instances where ‘Malarkey’ comes at the beginning of the attribute,
<a href=”/” title=”Malarkey is Andy Clarke” >Malarkey</a>
a[title^=”Malarkey”] { border-bottom : 1px dotted #900; }

(4) instances where ‘Malarkey’ comes at the end of the attribute,
<a href=”/” title=”Andy Clarke is Malarkey” >Malarkey</a>
a[title$=”Malarkey”] { border-bottom : 1px dotted #900; }

(5) or even titles which contain the word ‘Malarkey’ somewhere in the attribute.
<a href=”/” title=”Wot a handsome chap Malarkey is” >Malarkey</a>

a[title*=”Malarkey”] { border-bottom : 1px dotted #900; }


Comments are disabled.

%d blogcu bunu beğendi: