Introduction to CSS

What Is CSS?

CSS stands for Cascading Style Sheets. It’s used to control how HTML elements are displayed — including colors, fonts, spacing, and layout.

Why Use CSS?

CSS helps you separate the content (HTML) from the design (CSS). This makes your website cleaner, more organized, and easier to maintain.

  • ✅ Apply styles across multiple pages
  • ✅ Update styles in one place
  • ✅ Cleaner HTML structure

Ways to Apply CSS

  • Inline CSS: Directly inside an element
  • <p style="color: red;">Red Text</p>
  • Internal CSS: Inside a <style> tag in the head
  • <style>
      p { color: green; }
    </style>
  • External CSS: Separate file linked to HTML
  • <link rel="stylesheet" href="styles.css">

CSS Syntax

CSS uses a selector to target an element and apply one or more style declarations:

selector {
  property: value;
}

Example:

p {
  color: blue;
  font-size: 16px;
}

Common CSS Selectors

  • Type Selector — Targets all elements of a given type
    p {
      color: blue;
    }
  • Class Selector — Targets elements with a specific class (prefix with .)
    .highlight {
      background-color: yellow;
    }
  • ID Selector — Targets an element with a specific ID (prefix with #)
    #main-title {
      font-size: 24px;
    }
  • Universal Selector — Targets all elements
    * {
      margin: 0;
      padding: 0;
    }
  • Group Selector — Targets multiple selectors at once
    h1, h2, p {
      font-family: Arial, sans-serif;
    }
  • Descendant Selector — Targets elements inside another element
    div p {
      color: gray;
    }
  • Child Selector — Targets direct children only
    div > p {
      font-weight: bold;
    }
  • Attribute Selector — Targets elements with a specific attribute or attribute value
    input[type="text"] {
      border: 1px solid black;
    }
  • Pseudo-class Selector — Targets elements in a specific state
    a:hover {
      color: red;
    }

Benefits of External CSS

  • 🌐 Shared across multiple HTML pages
  • 🧼 Keeps HTML code clean and focused on structure
  • 🛠 Easier to update and manage styling consistently

Cascading Concept

CSS follows a "cascading" priority model:

  1. Inline styles (highest priority)
  2. Internal styles
  3. External styles (lowest by default)

Specificity and !important can override the default cascade.

Practice Prompt

Create a simple HTML page that links to an external CSS file. Style the body with a light background color and change the font to Arial.

<!-- index.html -->
<html>
  <head>
    <link rel="stylesheet" href="styles.css">
  </head>
  <body>
    <h1>Welcome!</h1>
    <p>This page is styled with CSS.</p>
  </body>
</html>
/* styles.css */
body {
  background-color: #f9f9f9;
  font-family: Arial, sans-serif;
}

You can copy and paste this code in your IDE to run!

Need Help?

Ask the AI if you need help understanding or want to dive deeper in any topic