Use Attribute Selectors to Fine Tune Your CSS

Here’s a quick tip for fine tuning your CSS declarations.

You can use attribute selectors to style an html element that contains an attribute with the value that you declare. This allows you to do a bunch of cool stuff – like style different “input” types differently, style anchor tags with titles differently, and etc.

How does it work?

An attribute selector follows this basic formula…

[attribute="value"] { style information... }

Like an id or class selector, you can use it alone (as in the example above), or attach it to a specific html element.

How can we use it? Here are a few examples.

Style Links with Title Elements Differently

You could use this to give users a hint that an anchor tag or link has a title element. This way they know to hover over the link and read the tooltip.

a[title] { border-bottom: thin dotted blue; }

That declaration gives any anchor tag containing a “title” attribute a thin dotted blue underlining. You may have to tweak it a bit to make sure the normal anchor-underlining doesn’t interfere with it.

Style Particular Input Types on Forms

You can use this to style Submit buttons, Text Inputs, etc. – independent of other input types.

input[type="submit"] {  background-color: blue; }

This simple declaration gives all Submit buttons a blue background color. Fairly silly, but the point is the declaration – not the actual styling. You could do something similar with these declarations…

input [type="text"] { /* style information */ }
input [type="password"] { /* style information */ }
Style Internal Links Different from External Links

This is a really nifty trick… but unfortunately it requires a bit of CSS 3. This will probably invalidate your CSS, and your mileage may vary.

It’s still interesting to try out.

You can use “^=” instead of “=” to signal that the browser should match any element with the given attribute that contains the quoted string. It doesn’t have to be an exact match. So you can use “^=’mydomain.com’” to match any links that point to the domain you’re working on.

Like so…

a[href^="earn-web-cash.com"] { /* style information */ }

You could use this to given internal links a slightly different color – some kind of queue to help the user differentiate between internal and external links.

For a longer list of ways to use this neat little trick, check out this post Hip to Be Square. There’s also a list of the different ways to search for values (like ^=) – which will be valid in CSS 3.

Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , , , ,

2 Comments to “Use Attribute Selectors to Fine Tune Your CSS”

  1. aSKer said this on

    I don

  2. Use Attribute Selectors to Fine Tune Your CSS | Web Cash | CSS Tutorials - CSSHelper.net said this on

    [...] Source [...]

Leave a Reply