CSS Basics

I. How to add CSS to HTML

There are two common ways to add CSS to 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 an external style sheet where we have a separate 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

A comment is a useful way to leave notes to ourselves or others if we are working on 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 class name, 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 on a page.

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

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

CSS specificity

If there are two or more CSS rules that apply to the same element, the selector with the highest specificity will display.

It helps resolve conflicts arising from multiple rules.

Here is the specificity hierarchy

  • Inline styles - Example: <p style="color: pink;"></p>.
  • #ID selectors - Example: #form-input.
  • .class, :pseudo-class, and [attribute] selectors - Example: .book, :hover, [href].
  • Tags and ::pseudo-element selectors - Example: h1, :before.