Hi Guys,
While working on css3 pseudo classes I came across this beauty, that could be handy just in few cases.
You can read more about attr() specs here http://www.w3.org/TR/css3-values/#attr
Anyway lets talk a little bit more about this function. Key things you should remember are
- In CSS3 attr() can return different types in contrast to CSS2 implementation where it would only return string
- Purpose of attr is data related not presentation related
- It must be used with attribute names such as data-*
There is better way to understand other than when its shown implemented.
Consider this example
The Markup
We will work with a basic markup and will only define a DIV as shown below
1 |
<div id="alt" data-phone="00613999999" data-name="Jaspreet Chahal" data-href="http://jaspreetchahal.org">Look up and down to know more about me</div> |
1 |
Nothing complicated in our DIV above. The only thing you should note is that I defined few custom attributes such as data-name, data-href, data-phone
The CSS
Now lets check the CSS side of things
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
#alt { display: inline-block; position: relative; min-width: 500px; } #alt:after,#alt:before { position: absolute; display: inline-block; } #alt:after { content:"My website is " attr(data-href) ; border-top:1px solid #0480be; left:0px; top:30px; } #alt:before { content:"My name is " attr(data-name) " and you can call me on " attr(data-phone); border-bottom:1px solid #0000CC; left:0px; top:-30px; } |
As you can see that we are using our attr() with content property and we are making use of our custom attributes and using them as fill values for blanks.
Demo
See above implementation in action by visiting the example page below
http://jaspreetchahal.org/examples/html5/attr.html
As you can see that CSS is becoming more powerful with every release with functions such as attr() being added/improved. I still sometimes wonder if that is actually an overhead when performance is something that you are looking for.
I hope this helps
Leave a Reply