Posts Filed Under ‘IDs and Classes’
CSS Attribute Selectors: Built-In Classes

If you’ve been a CSS groupie or follower of this website for any length of time, you should have a fairly firm grasp on the concept of using classes in XHTML as “hooks” into your pages (and if not, this article is a good place to catch up). But classes and IDs aren’t the only ways you can describe the elements in your website in order to style them. You can also make use of attribute selectors.
Attributes are the property=”value” pairs inside of most XHTML elements that further describe that element. Take the anchor tag, for example:
<a href="page.html" title="Click to visit!">Text</a>
This anchor tag has two attributes: href and title. Those attributes also have very specific values associated with them. And it’s these attributes, and their values, that make attribute selectors work.
By using attribute selectors in your CSS, you’re able to target elements with specific attributes, or even specific values within those attributes. When using attribute selectors, the attribute is contained within [brackets], just like how .classes have a leading period, or #ids have a leading pound sign. There are four ways to use attribute selectors:
The [attribute] syntax is the least specific of the four. It allows you to target any element with a specific attribute set, regardless of its value. For example:
a[title] {
font-weight: bold;
cursor: help;
}
This little bit of CSS would target any anchor tag that had a title attribute set, regardless of what the title contained. My CSS here makes the anchor boldfaced, and changes the cursor to a question mark when the user hovers over the link. This could be useful to indicate to the user that more information (i.e., the tool tip) is coming.
The most specific syntax is [attribute=”value”]. Using this selector, you’d be able to apply specific styles to elements with specific values set. So if, for example, you had an anchor that pointed to a specific website you wanted to emphasize:
a[href="http://www.cssnewbie.com/"] {
font-size: 120%;
color: red;
}
This code would add a bit of emphasis to any link going to the front page of CSSnewbie. I would recommend copying and pasting this code into any website you happen to be working on at the moment. :)
The [attribute~=”value”] syntax allows you to look within the attribute’s values and find a specific value within a space-separated list of values. Alternatively, you can use the related [attribute|=”value”] syntax to find parts of a value that are separated by hyphens (instead of spaces). So, for example, if I had an image with an alt tag that read “Gallery: Wombats Gone Wild,” I could style this gallery (and all other galleries that followed this same pattern) like so:
img[alt~="Gallery:"] {
border: 2px solid #333;
}
And suddenly, all of your images that link to galleries have special styling, without having to add any additional classes! And that’s really the beauty of attribute selectors: if used properly, they can be a great help in the fight against Classitis.
Of course, attribute selectors don’t work everywhere (why would they? They’re too cool for school). Here’s where attribute selectors earn a big fat FAIL:
- IE6 or below on the PC
- IE5 or lower on the Mac
- Netscape 4 or under (i.e., people in 1997)
- Both people still using Opera 3
Luckily, very few people are still using Opera 3, Netscape 4, or IE5. And with the recent release of IE7 (and the planned future release of IE8), Internet Explorer version 6 should be on its way out the door, as well. In other words, attribute selectors are fast becoming a reasonable means of styling your websites.
Combating Classitis with Cascades and Sequential Selectors

There is a disease out there in the CSS world. It can afflict anything from the meanest weblog (or the nicest ones too, I suppose) to the greatest of corporate websites. It’s called Classitis, and I’ve encountered it far too often in my professional work. Perhaps you’ve seen it too. It looks a little something like this:
body {
font-family: Arial; }
h1 {
font-family: "Times New Roman"; }
h2 {
font-family: "Times New Roman"; }
p {
font-family: Arial; }
p.ArialRed {
font-family: Arial;
color: red; }
p.ArialRedBig {
font-family: Arial;
color: red;
font-size: 150%; }
ul {
font-family: Arial; }
ul.ArialRed {
font-family: Arial;
color: red; }
strong.redArial {
font-family: Arial;
color: red; }
This particular snippet of (completely fictional) horribly afflicted CSS suffers from multiple problems which could all probably be considered symptomatic of Classitis, even when they don’t directly involve classes. I’ll go through the five of the most glaring problems and how to remedy them below.
The Cascading ability of CSS is ignored. Notice how many times the “font-family: Arial;” rule is applied? This is a waste of space, and ignores the fantastic cascading ability of CSS (which I’ve covered elsewhere). Once the appropriate font family had been applied to the body tag (the first rule in our example), all of the additional “Arial” family declarations, because they were identical and were inherited from this first declaration, became redundant.
Simple and identical rules are repeated. Take a look at the rules for the <h1> and <h2> tags in the example above. They use a different font-family than the body tag, so it’s appropriate that they have a rule making that change. But why repeat the rule twice? With CSS, you’re allowed to list sequential selectors, separated by a comma. Instead of the rule above, we could’ve written this:
h1, h2 {
font-family: "Times New Roman"; }
Different classes have an identical effect. Consider the rules “ArialRed” and “RedArial” above. They do exactly the same thing, but the designer was in such a hurry, they accidentally created two rules that mirror one another. Always stop and consider when you’re writing your CSS if there’s any way to consolidate your rules. If you have to write the same rules multiple times, the answer is probably “yes.”
Classes are applied to multiple elements. There are two instances of the “ArialRed” class in the example above. One is being applied to a paragraph tag, while the other is being applied to an unordered list. There’s no need for this redundancy. By eliminating the “p” and “ul” portions of the two selectors, those classes can be consolidated into a single instance.
Class names are super long. This is the classic symptom of Classitis from whence the name derives, much like how chicken pox is named after the chicken-shaped virus that causes it (no? Well, you figure it out then). Designers sometimes get in a hurry and start building classes for every possible design difference they encounter. This can most easily be combated by remembering two things:
First, as I’ve mentioned before, elements can have multiple classes. Instead of having a class of “RedBig,” why not break it into two classes? Then you can style elements that need both classes like this:
<p class="red big"> This text is now red and big. </p>
Second, classes should describe what an element does, not what it looks like. A class of “red” is great when you’re first building a site, but what happens three months down the road when you decide that you want your emphasized text to be blue? A class of “.highlight” or something similar to indicate the text should stand out in some way would have been more appropriate. Of course, even seasoned developers tend to break this rule every once in a while.
So, after we apply all of the advice offered above, what are we left with? Something that looks a little like this:
body {
font-family: Arial; }
h1, h2 {
font-family: "Times New Roman"; }
.highlight {
color: red; }
.shout {
font-size: 150%; }
Ahh… nice, healthy CSS, without all of the bloating Classitis inevitably causes.
Of course, these are just a few of the pitfalls of redundancy and excess that designers can fall into when developing their CSS. If you can think of others, share them in the comments.
The 4 CSS Rules of Multiplicity

One quick and easy way to keep your CSS clean and well-structured is to remember (what I’m going to title) the four CSS Rules of Multiplicity. They are:
- Multiple declarations can live in a single rule.
- Multiple selectors can preface the same rule set.
- Multiple rules can be applied to the same selector.
- Multiple classes can be set on a single element.
Multiple declarations in a single rule is the most fundamental of the four CSS Rules of Multiplicity. Simply stated, it means you can have as many CSS declarations as you want between your opening and closing braces, like so:
body {
property-1: value;
property-2: value;
...
property-infinity: value;
}
Multiple selectors can really help keep your CSS clean by grouping your rules together. Consider the following example:
p {
font-size: 110%;
color: #333;
}
ul {
font-size: 110%;
color: #333;
}
When rules are identical like this, you can combine them by using sequential selectors, like so:
p, ul {
font-size: 110%;
color: #333;
}
But what happens when you have two selectors that have very similar, but not quite identical, properties? That’s when multiple rules come into play. Here’s an example:
p {
font-size: 110%;
color: #333;
}
ul {
font-size: 110%;
color: #333;
font-weight: bold;
}
The paragraph and unordered list share a few properties in common, but not all. But you’re allowed to refer to the unordered list more than once, so you could write something like this:
p, ul {
font-size: 110%;
color: #333;
}
ul {
font-weight: bold;
}
Another way to tackle having multiple rules in common across elements is to create multiple classes. For example, you could create a rule like this:
.container {
padding: 5px;
border: 2px solid #ccc;
background-color: #f2f2f2;
}
But then a while later, you decide you want something that is almost the same as your container class, but the text within is larger and boldfaced. You might be tempted to write a completely new class that includes the padding, border, background, and font size and weight that you need. But instead, you could just create a second class containing just the differences between the two, like this:
.strong {
font-size: 150%;
font-weight: bold;
}
And then apply both classes to your XHTML element thusly:
<div class="container strong"> This text is in our container, but is also big and bold. </div>
By using all four of these examples of multiplicity together, you can keep your CSS looking lean and clean. And luckily, unlike the movie version of Multiplicity, Michael Keaton doesn’t get dumber the more often you use them.
Style your links with CSS

Anchor tags (a.k.a. links or hyperlinks) (these things: <a>) are one of the more ubiquitous elements of the web world. In fact, it’s the anchor tags that put the ‘Web’ in the World Wide Web – they’re the points of interconnectivity, like strands in a spider web, that hold this whole crazy Net of ours together.
And we all know what links look like, too: they’re dark blue, underlined, and stand out on a page like the varicose veins on the backs of great-Aunt Esther’s legs. And just as we don’t understand why Esther would choose to wear those shorts in public, we don’t understand why something as common as an anchor tag should have to look so darn unattractive.
With CSS, links don’t have to be ugly.
But here’s the kicker: with CSS, links don’t have to be ugly. They can look pretty much however you want. Here are a few of the things you can do to make your links stand out without sticking out:
Change the Color. Some stick-in-the-mud Web proponents would have you believe that blue is the only color a hyperlink should ever wear, in much the same way that white shoes after Labor Day are a social faux-pas. Their argument is that people are used to seeing blue, underlined links; to mess with this convention is to anger the gods and confuse your readers. I say bollocks! Any text that stands out from the rest will attract attention. And green can stand out just as well as blue:
a {
color: #6c6;
}
This gives us a lovely link the exact shade of a seasick leprechaun. How’s that for fancy?
Underline, Schmunderline. Personally, I’m not a big fan of underlined text. Too much of it can be a distraction – everything on the page seems to be clamoring for attention. So why don’t we remove the underline from that hyperlink:
a {
text-decoration: none;
}
And now, our links don’t overwhelm the nearby text.
Or, you could even make the underline only appear when someone puts their mouse over the link (my personal favorite):
a {
text-decoration: none;
}
a:hover {
text-decoration: underline;
}
The rules above state that “normal” anchor tags should not have any sort of decoration: no underlines, in other words. However, when someone “hovers” over an anchor, we should put the underline back.
Image is Everything. If you wanted to get really fancy, you could even make a small image (an icon, if you will) appear next to your links. All you have to do is create your image at the appropriate size, put it on your server where your CSS can get to it, and do something like this:
a {
padding-left: 16px;
background-image: url(icon.gif) no-repeat;
}
This rule is a little more complicated, so I’ll explain in greater detail. First, we applied some padding to the anchor tag… we need some room for the image to show up. Then, we applied the image to the background of the element (which, as we learned last time, is applied to the padding around an element). Under normal circumstances, the background would repeat itself in every direction, showing up underneath our link text. We don’t want that, so we added the ‘no-repeat’ condition to stop it from showing up more than once. And the result: links with images.
Putting it All Together. When our powers combine, we become… Captain Hyperlink! Or, at the very least, we can have aesthetically pleasing links that somehow manage to attract attention without overwhelming the page. And without reminding us of great-Aunt Esther’s visit last summer.
If we take what we know about CSS classes and apply that to this example, we could even make certain types of links look different from others:
a.pdf {
color: #c00;
font-weight: bold;
text-decoration: none;
padding-left: 10px;
background-image: url(pdf_icon.gif) no-repeat;
}
a.pdf:hover {
text-decoration: underline;
}
Now how’s that for some fancy linkage? I encourage you to take these examples I’ve provided and expand upon them. What can you make your links do?
When to Use CSS IDs and Classes
There are three different ways in CSS you can dictate which elements you want to style. Each way is useful for a specific set of purposes, but by using all three together, you can really harness the cascading power of style sheets. The three methods of describing objects on a page are by their tag name, their ID, or their class.
First and most obviously, you can style all of an entire subset of elements by styling a specific tag. For instance, take the following code (please!):
p { color: red; }
This states that all text within a paragraph <p> tag anywhere in your document should be colored bright red, like so. As with most of my code examples, this practice is ill-advised but hopefully illuminating nonetheless. This technique is most useful when you want to change a large number of elements on your page at once.
However, you can also describe elements according to their IDs and their classes. Both IDs and classes are ways of further clarifying which elements you’re planning to alter. So consider the following snippet of HTML:
<p id=”introtext”>This is a snappy introduction.</p>
<p class=”aside”>Okay, so the intro isn’t that great.</p>
Here we have two paragraphs, one of which has an id assigned, and the other which has a class. You could manipulate these two paragraphs independently of one another (and the other regular paragraphs in your document) with code such as this:
p#introtext { font-size: 150%; }
p.aside { font-style: italic; }
IDs are unique and beautiful snowflakes. Classes are not.
The first rule affects our “introtext” paragraph. We select that specific element with “p#introtext,” with a pound sign between the two elements, which means “paragraph tags with an id of introtext.” We’ve set its font size to be 1.5 times the size of a normal paragraph tag.
Our aside, on the other hand, uses a period between the element and the class, which lets the browser know we’re talking about classes instead of IDs. And you don’t even technically need the “p” identifier before the ID or class: styling simply “#introtext” or “.aside” would have worked just as well in this example, but the more specific you are, the less danger you’re in of accidentally styling things you didn’t mean to.
So what’s the difference between an ID and a class, then? It’s pretty simple: IDs are unique and beautiful snowflakes (just like you!). Classes are not.
Think of an ID something like the license plate on your car. It’s an identifier that, presuming you haven’t been a victim of theft, is unique to your vehicle. Similarly, an ID can only be used once per HTML document. So if you have something on your page that you need to be different from everything else, that is a good time to set an ID.
A class, on the other hand, can be applied to multiple elements on the same page. So, going back to our CSS example above, we’re saying that our page will have only one introduction, but can or will have multiple asides. Sort of like this article, when you get right down to it.
Another important distinction between the two is that each element on your page can have only one ID, but can have multiple classes. So you could have HTML like this:
<p class=”aside right”>Was this example really necessary?</p>
You could then have two classes defined in your CSS: one that does something specifically to asides, and another that does something to elements with a class of “right” (for example, it could float them to the right side of the page). Elements with just an “aside” class would only have the “aside” attributes applied, while elements with just the “right” class would just be floated right. But by applying both to one element as we have above, we can create a unique type of element without having to write a lot of extra code. And that’s what CSS is all about.














![Click here for more information. [your ad here] Become a Sponsor! Click here to learn more.](/img/your-ad-here.gif)