Topics covered

CSS - what is that?

CSS is used to style your HTML elements. You can manipulate the colors, margins, positions and many other properties of elements. This is done through the rules you write. Sometimes more than one rule applies to an element, so CSS decides which properties are actually applied to the element in case the two rules conflict with each other. This is the “cascading” part of our Cascading Style Sheet.

Start with inline styles

To get you started, you can insert a style tag inside of your head tag:

<head>
  <meta charset="UTF-8">
  <title>Our Page Title</title>
  <style>
    /* CSS styling rules here. Yes, comments are different in CSS. It’s not our fault! */
  </style>
</head>

Basic CSS syntax

CSS has a simple syntax. CSS styling consists of a list of rules. Each rule consists of one or more selectors and a declaration block. Your selectors identify your HTML elements, so they are used to declare which part of the markup a style applies to. Let’s take the h1 title we wrote in our HTML file and give it a nice red color:

h1 {
  color: red;
}

h1 is the selector, the HTML element we want to style. color is one of the properties that we can give to our selector, and red is the value of this property. The pattern of CSS syntax is:

selector {
  property: value; /* remember always to write a ; after your value. */
  property: value;
}

Refresh your browser (CMD + R) and see how the color of your title has changed. Wow, so red! Isn’t this nice?

Useful CSS properties

Now, let us insert a div and style it a little bit. So parts of your file should look like this:

<head>
<!-- ... -->
  <style>
    div {
      color: white;
      background-color: green;
      width: 300px;
      height: 200px;
    }
  </style>
</head>
<body>
  <div>I’m a div</div>
</body>

So now if you save and hit refresh, you should see a green block with some white text stating “I’m a div” on it. Here you see some properties, you already know color. There is also background-color, width and height.

Shorthand

On some occasions you might see properties defined in different ways but doing the same thing, such as:

selector {
  border-width: 1px;
  border-style: dotted;
  border-color: green;
}

anotherselector {
  border: 1px dotted green;
}

This is what we call shorthand. Some properties have a shorthand format that allows us to define more properties at once, but just in one line. The order and the way it works is not always very obvious so you might need to look it up on a reference, but don’t worry too much about it. For now, it’s good to know it exists in case you see it somewhere else. If you think it’s confusing, use the non shorthand format for your own code and specify each property at a time.