How to Write a CSS Rule

So if you’ve read “What is this CSS thing, anyway?” (which I’d recommend doing), you have a basic understanding as to what CSS is on a theoretical level. And I’m sure you’re a better person for it. But what about the practical details? How do you actually put together a CSS rule that will style your HTML? Read on, dear friend. Read on.

The styntax of CSS is extremely simple to understand.

Join us in our newest publication:

The syntax of CSS is extremely simple to understand. A CSS file is essentially a list of rules. And each of those rules is comprised of two basic parts: a selector and one or more declarations. Each declaration also consists of two parts: a property and a value. In the end, every rule ends up looking like this:

selector {
property: value;
property: value;
...
property: value;
}


Easy, right? You lead off with your selector, open up a curly brace to contain all your declarations, give a property, followed by a colon, followed by one or more values that you want attributed to that property, and then end the declaration with a semicolon to signal you’re done. Then you close the whole thing with a closing curly brace and move on to your next selector. You don’t even have to format your text the way I have above: the spaces are purely to make it easier for we humans to read. Your HTML page would do just fine if all your rules were on the same line. I wish my grocery list were this straightforward.

That’s all there is to know about the syntax of CSS. The rest is largely learning how selectors work, figuring out which properties to use, and learning which values create which results. I’ll offer a few pointers below.

Selectors: These can be page elements (like ‘strong’ for the <strong> tag), IDs, classes, and even pseudo-elements or any combination of these (watch for an article explaining how to use IDs and classes in the near future). This means that selectors can get a little complex at times:


div.message p#alert strong a:hover {
color: red;
}

But all this rule is saying is that if there is a div with a class of “message,” containing a paragraph with an ID of “alert,” containing a strong tag, containing an anchor tag that is being hovered over (the cursor is over the link), then that link should be red. Once you understand the basic principles behind reading a CSS selector, rules like this become very easy to create.

Declarations: Unlike the infinite variety possible in selectors, there are a finite number of properties and values, which are determined by the World Wide Web Consortium (W3C) as part of the CSS Specification. In “Understanding the CSS Box Model,” we covered the properties of border, background, padding, width, and margin. To see a full list of CSS properties, values, and how they interact, check out this excellent list of printable PDF cheat sheets.

Share and Enjoy !

0Shares
0 0