CSS Basics

I. How to add CSS to HTML

There are 2 common ways to add CSS in our HTML:

  • Internal CSS
  • External CSS

1. Internal CSS

We can add internal CSS directly in the <head> section by enclosing the code in <style> tags.

<head>
  <style>
    h2 {
      color: white;
      background-color: black;
    }
  </style>
</head>

2. External CSS

A better way to add CSS is to use external style sheet where we have a seperate CSS file and link it to our HTML.

In our head section, we add:

<head>
  <link href="style.css" type="text/css" rel="stylesheet" />
</head>

II. Comment

Comment is a useful way to leave notes to ourselves or others if we are working in a project.

A CSS comment starts with /* and ends with */

/* Comment here*/

Shortcut

We can use a shortcut for comments:

  • On MacOs: cmd + /
  • On Windows: ctrl + /

III. Classes and IDs

ID is an individual while Class is a group.

1. Class

In CSS, the class attribute is referenced using a dot

.class-name {
  /* CSS code */
}

We can include the element before the classname, but we don’t need to.

div.hello {
  /* CSS code */
}

2. ID

ID is unique so we can only have 1 ID of this name in a page.

In CSS file, we use hashtag # before the ID name

#element-id {
  /* CSS code */
}