Monday, November 8, 2010

CSS Inheritance

From http://dorward.me.uk/www/css/inheritance/

(Another good link is - http://www.webdesignfromscratch.com/html-css/css-inheritance-cascade/)

Multiple Classes

Making good use of classes will solve most problems. Take the example of having boxes of data floating on alternating sides of the canvas.

.oddBoxOut {
width: 12em;
float: left;
padding: 0.5em;
margin: 0.5em;
border: solid 1px black;
}

.evenBoxOut {
width: 12em;
float: right;
padding: 0.5em;
margin: 0.5em;
border: solid 1px black;
}

As you can see, many properties are duplicated in each definition, so it is obvious why somebody might want OO-style inheritance.

There is another solution though. Lets take a quick look back at the HTML specification:

class = cdata-list[CS]
This attribute assigns a class name or set of class names to an element. Any number of elements may be assigned the same class name or names. Multiple class names must be separated by white space characters.

So we can assign multiple class names to a single element? That means we can change the style sheet so it looks like this:

.boxOut {
width: 12em;
padding: 0.5em;
margin: 0.5em;
border: solid 1px black;
}

.oddBoxOut {
float: left;
}

.evenBoxOut {
float: right;
}

And then the HTML will look like:

<div class="boxOut oddBoxOut">

Grouping Selectors

A single style may have multiple selectors assigned to it through the use of grouping.

To revisit the previous example, we first simplify the HTML so we only mention the one class:

<div class="oddBoxOut">

Then we assign the CSS we want to it, but we group the common property/value pairs.

.oddBoxOut,
.evenBoxOut {
width: 12em;
padding: 0.5em;
margin: 0.5em;
border: solid 1px black;
}

.oddBoxOut {
float: left;
}

.evenBoxOut {
float: right;
}

These two techniques should solve most problems which people think can be solved with OO-style inheritance, but we still have the option of using a preprocessor.

No comments:

Post a Comment

Followers

Blog Archive