oblaat

a guide to conceiving, creating & publishing your own website

Rules in CSS

Each line of CSS that defines how a certain part of a HTML document should look is called a rule. Like any other computer language, you write a set of instructions, but CSS may be even easier to read for a newcomer than HTML.

In HTML, a document requires shorthand for paragraph and first-level heading. In CSS, most of the rules are written using full words, aside from the HTML elements themselves. If you know how CSS is formatted and see something new, chances are you can guess what it does before even looking it up. Could you guess what this piece of CSS does?

h1 {
    color: red;
    text-align: center;
}

If you guessed that this makes a first-level heading red and it centers the text, you would be correct. As CSS is designed to be written just a bit less frequently than your standard HTML tag, the code needs to be memorable. What could be more memorable than a direct description of what you want to do?

A rule is made of three parts: the selector, the property, and the value. These parts are divided neatly with curly braces, colons and semicolons.

The selector tells the browser what part of the document is affected by the provided rules. This is always a HTML element, but the specificity of the selector can be at any level.

You might apply one rule to every single paragraph, and another rule to an element of any type with the class "deco". You could even apply a rule to every third entry in an unordered list, as long as it's inside of navigation, provided it does not have an image inside of it. (Somehow that one is easier to understand if you read it in CSS code.)

The property is the thing that is being defined, and the value is (predictably) what that property is supposed to be. The color property has the value of red. One selector can have multiple rules, as in the above example, and it's customary to separate the property-value pairs with line breaks for nicer reading and organisation.

These rules cascade in unique and useful ways: if you decide that the body tag should have all of its text written in blue, then every paragraph inside of the body will also have blue text.

However, any CSS rule that is more specific than whatever is previously defined will take precedence. If one rule says that all paragraphs must be displayed in Helvetica, but another rule demands that links are written in Times New Roman, a link inside of a paragraph will be written in Times New Roman and not Helvetica. This link is considered "more specific" than the paragraph.