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:

Join us in our newest publication:
  • 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.

Share and Enjoy !

0Shares
0 0