Learning CSS, Part 2 – Syntax

Welcome to Part 2 of the Learning CSS series.

In Part 1, we learned what CSS is and how we can use it in our own web site. In this article we are going to touch on the basic syntax of CSS.

HTML has tags, CSS has a selector and one or more declarations. Selectors are the elements you want to style. As an example:

p {
     color: red;
     margin-left: 10px;

the selector is p and the declarations are color: red and margin-left: 10px;.

Each declaration consists of a property and value. Above the properties are color and margin-left; the values are red and 10px.

There are many different units that can be used for property values. Some of the general units used in a number of properties:

  • em (font-size: 2 em) is the unit for calculating the size of a font (see below for an explanation)
  • px (font-size: 12px) is the unit for pixels
  • pt (font-size: 12pt) is the unit for points
  • % (font-size: 80%) is the unit for percentage

To explain how em works, see the following code:

.your_element {
    font-size: 10px;

The above is basically saying that 1em = 20px. But, lets say that you add some more styling, as below:

.your_element {  
    font-size: 20px;  
    width: 2em;  
    height: 2em;  

Now guess what happens. If 1em = 20px in the first code example, then now the height and width gets calculated as 20px x 2em or 40px. Now you are asking “What if there are no font-size properties declared on the page(s)? Good question. The answer is the value of a single em unit will be equal to 16px. 16px is the default. Also, remember that the font-size property inherits throughout the document, the em unit’s value will be calculated from whatever is actually inherited, just as the above example shows.

Remember this when designing your web site – px does not allow for re-sizing and can cause display problems when your web page / site is viewed. Using em for the font size avoids re-sizing problems with older Internet Explorer versions and possibly other browsers. This is also a recommendation by the W3C.

Also, keep in mind, when you declare a value of 0 (zero) you do not need to designate a unit. So if you want to style your header and want to keep the bottom margin at zero, you would use the following:

Well, that is it for Part 2 of this series. In Part 3 of Learning CSS we are going to learn how to provide some color to a web page using CSS.

Posted in Web Design and tagged .

Leave a Reply