Skip to main content

Lesson 2: Styling Text and Colors

Text Properties

CSS provides a wide range of properties to style and control the appearance of text. Below are some of the most commonly used text-related properties:

  1. font-family: Defines the font for an element.

    p {
    font-family: 'Arial', sans-serif;
    }
  2. font-size: Specifies the size of the text. You can use different units like px, em, or %.

    h1 {
    font-size: 32px;
    }
  3. font-weight: Controls the thickness of the text (e.g., normal, bold, or numerical values like 400, 700).

    p {
    font-weight: bold;
    }
  4. text-align: Aligns the text horizontally (e.g., left, center, right, or justify).

    h2 {
    text-align: center;
    }
  5. line-height: Adjusts the space between lines of text.

    p {
    line-height: 1.5;
    }
  6. text-transform: Alters the text's capitalization (e.g., uppercase, lowercase, or capitalize).

    h1 {
    text-transform: uppercase;
    }
  7. letter-spacing: Increases or decreases the space between letters.

    p {
    letter-spacing: 2px;
    }

Color Values and Backgrounds

CSS allows you to define colors in various ways. Here are the most common color formats:

  1. Color Names: You can use predefined color names like red, blue, or green.

    h1 {
    color: red;
    }
  2. HEX Values: A six-character hexadecimal value, starting with a #, representing the color.

    h1 {
    color: #3498db; /* light blue */
    }
  3. RGB and RGBA: Represents colors using Red, Green, and Blue values, each ranging from 0 to 255. The A in RGBA is for opacity (0 for transparent, 1 for fully opaque).

    h1 {
    color: rgb(52, 152, 219);
    }
    p {
    background-color: rgba(52, 152, 219, 0.5); /* semi-transparent */
    }
  4. HSL and HSLA: Stands for Hue, Saturation, and Lightness, with A again representing opacity.

    h1 {
    color: hsl(207, 71%, 53%);
    }

CSS Units

When styling elements, you will encounter various units for properties like font size, padding, and margins. Here are the most common:

  1. px (Pixels): A fixed unit that represents a single pixel on the screen.

    p {
    font-size: 16px;
    }
  2. em: Relative to the font size of the element. For example, 2em is twice the size of the current font.

    p {
    font-size: 1.5em; /* 1.5 times the parent element's font size */
    }
  3. rem: Relative to the root (html) font size, which is useful for maintaining consistent sizing across the site.

    p {
    font-size: 1.2rem;
    }
  4. %: Relative to the parent element, often used for fluid layouts and responsive design.

    div {
    width: 80%;
    }