
21 November 2006
With CSS, it's possible to use more than one class on any (X)HTML element. This is a useful technique that can help avoid CSS style sheet bloat. Here's an example that I used recently.
I wanted to style a photo with a pale grey border and align the image right. I also needed a margin of 10px, padding of 5px, and background color #FFF - to create a 'photo paper' type effect and move the image away from any adjacent text. This is the CSS rule:
.photo {
margin: 10px;
padding: 5px;
background: #FFF;
float: right;
border: 1px solid #E0E0E0;
}
and the (X)HTML with my image attributes:
<img src="images/lime.jpg" class="photo" alt="Lime" width="250" height="188" />
Imaginatively, I called the class 'photo' and it does the job just fine. However, it would also be useful to have the same style rule but with the photo on the left. In the past, I might have created a new style rule (perhaps, called photo2?!) with most of the same styles. However, this leads to style rule duplication - and there's no need to do it. Instead, create a second rule like this:
.left {
float: left;
margin-right: 20px;
}
In this case, I assign a rule for floating left, and change the right hand margin a tad because it looks better on my page. Now, it's easy to switch an image from right to left by assigning multiple classes, 'photo' and 'left', to any image tag. Multiple classes on any element are separated by a space. Rules from the second class will take precedence over the first class. Like this:
<img src="images/lime.jpg" class="photo left" alt="Lime" width="250" height="188" />
In this case, the image uses the same style rules from class 'photo' but the two style rules from class 'left' also apply and override the float and right margin values. Therefore, the position and right margin for the second image will change. See the final example here.
This method can allow quick and simple changes, on images in particular, but can be used for any element where common rules apply in most cases - but where specific rules are used in some examples.
I like multiple classes because it allows me to have a 'CSS switch' for common page elements, like images, blockquotes, and paragraphs. Use multiple classes selectively with descendant selectors and you will soon be producing lean and mean style sheets that are easier for everyone concerned.
More: Further reading on class selectors
» UK2 for web hosting. From £4.17/month. Free Google AdWords Voucher
Great! Just what I was looking for.
Thanks!
(Who could have known it would be so simple :P)
· Oliver Jan 9, 09:36 AM 1
Hi!
Like the site; and you won’t regret the move to Drupal!
The concept of descendant classes hadn’t really struck as being a CSS use of multiple inheritance; I see it now! Thanks.
Pete.
· Pete Barnett Aug 9, 03:18 AM 2
@Pete. Actually, I use Textpattern for this site. I don’t use Drupal. Sorry!
· Clive Walker Aug 9, 07:54 AM 3