Introduction to CSS and Styling

Week 4: Tuesday Morning Session

Welcome to CSS!

Today we're embarking on an exciting journey into the world of Cascading Style Sheets (CSS) - the styling language that transforms plain HTML documents into visually appealing websites. If HTML is the skeleton of a webpage, CSS is the skin, clothes, makeup, and overall appearance. Without CSS, the web would be a plain, text-only experience reminiscent of the early 1990s.

In this session, we'll explore the fundamentals of CSS, learn about its relationship with HTML, and start building the skills you'll need to create beautiful, responsive web designs.

File Organization

Before we dive in, let's talk about file organization. For your CSS files:

For this session, we'll be working with a file named main.css in a folder called styles.

What is CSS?

CSS (Cascading Style Sheets) is a style sheet language used to describe the presentation of a document written in HTML. CSS describes how elements should be rendered on screen, on paper, in speech, or on other media.

Think of CSS as a set of instructions for the browser - like a detailed painting guide that explains exactly how the HTML structure should look to the user.

CSS Analogy: The Building Metaphor

Imagine building a house:

The Evolution of CSS

Before CSS, styling a webpage required using HTML attributes and tags like <font> and bgcolor. This approach had several problems:

CSS solved these problems by separating content from presentation, allowing for:

How to Add CSS to Your HTML Documents

There are three ways to incorporate CSS into your web pages:

1. External CSS (Recommended)

External CSS involves creating a separate .css file and linking to it from your HTML document. This is the preferred method for most websites.

In your HTML file's <head> section:

<head>
    <link rel="stylesheet" href="/styles/main.css">
</head>

In styles/main.css:

body {
    font-family: Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f4f4f4;
}

h1 {
    color: #0066cc;
}

Real-world application: External CSS is like having a company style guide that ensures consistent branding across all materials. Large websites might have multiple CSS files for different sections or features, all working together for a cohesive look.

2. Internal CSS (Style Element)

Internal CSS is defined within a <style> element in the <head> section of an HTML document.

<head>
    <style>
        body {
            font-family: Arial, sans-serif;
            background-color: #f4f4f4;
        }
        h1 {
            color: #0066cc;
        }
    </style>
</head>

Use case: Internal CSS is useful for single-page documents or when you need page-specific styles that differ from your main website. Think of it like special decoration for just one room in your house.

3. Inline CSS (Style Attribute)

Inline CSS applies styles directly to individual HTML elements using the style attribute.

<h1 style="color: #0066cc; font-size: 32px;">Welcome to My Website</h1>

Use case: Inline CSS should be used sparingly, primarily for unique, one-off styling needs or when styles need to be applied dynamically (e.g., through JavaScript). It's like hanging a single, special picture frame that doesn't match any others in your house.

The Cascade: Why "Cascading" is in the Name

The "cascading" in CSS refers to how styles are applied and prioritized. When multiple style rules conflict, a specific order determines which rule "wins." The cascade follows this priority (from highest to lowest):

  1. Inline styles (style attribute)
  2. Internal and external stylesheets (determined by order and specificity)
  3. Browser default styles

This is like layers of authority in a organization - the CEO's decision (inline style) overrides the department manager's policy (internal/external CSS), which overrides the employee handbook (browser defaults).

CSS Syntax: The Building Blocks

Understanding CSS syntax is like learning the grammar of a new language. Let's break down the components:

selector {
    property: value;
    another-property: value;
}

Example:

h1 {
    color: blue;
    font-size: 24px;
    margin-bottom: 15px;
}

Let's analyze this:

Analogy: Think of CSS as a series of instructions for a painting:

Common Syntax Errors to Avoid

Pro tip: Modern code editors like VS Code will highlight syntax errors and provide autocompletion to help avoid these mistakes!

CSS Selectors: Targeting Elements

Selectors are patterns that match HTML elements. They're how you specify which elements should receive a particular style. Mastering selectors is crucial for efficient CSS.

Basic Selector Types

Element Selector

Targets all instances of a specific HTML element.

p {
    line-height: 1.6;
    margin-bottom: 15px;
}

This applies styles to all <p> elements on the page.

Class Selector

Targets elements with a specific class attribute. Use a period (.) before the class name.

/* In CSS */
.highlight {
    background-color: yellow;
    font-weight: bold;
}

/* In HTML */
<p class="highlight">This paragraph will be highlighted.</p>

Real-world use: Classes are like categories or tags for styling. Just as you might categorize clothes as "casual," "formal," or "athletic," classes help organize elements for styling purposes. A single element can have multiple classes, separated by spaces.

ID Selector

Targets a single element with a specific ID attribute. Use a hash (#) before the ID name.

/* In CSS */
#header {
    background-color: #333;
    color: white;
    padding: 20px;
}

/* In HTML */
<div id="header">Website Header</div>

Important: IDs must be unique on a page. Think of them like Social Security numbers - each person gets exactly one, and no two people share the same number.

Combining Selectors

You can combine selectors to target elements more precisely:

/* Targets paragraphs with the class "note" */
p.note {
    font-style: italic;
    color: #666;
}

/* Targets elements with both "alert" and "error" classes */
.alert.error {
    background-color: #ffdddd;
    border: 1px solid #ff0000;
}

Selector Specificity: The Rules of Precedence

When multiple selectors target the same element with conflicting styles, specificity determines which one wins.

Specificity hierarchy (from lowest to highest):

  1. Element selectors (e.g., p, h1)
  2. Class selectors, attribute selectors, pseudo-classes (e.g., .highlight, :hover)
  3. ID selectors (e.g., #header)
  4. Inline styles (using the style attribute)

Analogy: Specificity is like security clearance in a classified facility. Someone with "Top Secret" clearance (ID selector) can override decisions made by someone with "Secret" clearance (class selector), who can override someone with "Confidential" clearance (element selector).

/* Specificity battle example */
p {
    color: blue;              /* Least specific */
}
.text {
    color: red;               /* More specific */
}
#unique {
    color: green;             /* Most specific */
}

<p class="text" id="unique">What color will I be?</p>

In this example, the text will be green because the ID selector has the highest specificity.

Working with Colors in CSS

Colors are fundamental to web design. CSS offers several ways to specify colors.

Color Notation Methods

1. Color Names

CSS recognizes 140+ color names like red, blue, green, purple, etc.

h1 {
    color: navy;
}
button {
    background-color: tomato;
}

Best for: Quick prototyping or when exact color precision isn't critical.

2. Hexadecimal Colors

Six-digit codes preceded by a hash (#) representing RGB values in base-16.

body {
    background-color: #f5f5f5; /* Light gray */
}
footer {
    background-color: #1a1a1a; /* Very dark gray */
    color: #ffffff;            /* White */
}

Each pair of characters represents red, green, and blue values from 00 (none) to FF (maximum).

Shorthand: When each color channel has repeating digits, you can use 3-digit shorthand:

#ff0000 → #f00  /* Red */
#00ff00 → #0f0  /* Green */
#0000ff → #00f  /* Blue */
3. RGB and RGBA

Specifies red, green, and blue values on a scale of 0-255. RGBA adds an alpha channel for transparency (0-1).

header {
    background-color: rgb(30, 144, 255);  /* Dodger blue */
}
.overlay {
    background-color: rgba(0, 0, 0, 0.5); /* Semi-transparent black */
}

Real-world use: RGBA is particularly useful for creating overlays, shadows, and transparent elements that let content underneath partially show through.

4. HSL and HSLA

Represents colors using Hue, Saturation, and Lightness. HSLA adds an alpha channel.

.brand-color {
    color: hsl(204, 70%, 53%);       /* Blueish */
}
.tooltip {
    background-color: hsla(50, 100%, 50%, 0.8); /* Semi-transparent gold */
}

Advantage: HSL makes it intuitive to create color variations. Keep the same hue (first value) and adjust saturation or lightness to create related colors that work well together.

Color Psychology and Web Design

Colors evoke emotional responses and have cultural associations:

Real-world application: Notice how financial websites often use blue to convey trust, while sale prices are frequently highlighted in red to create urgency.

The CSS Box Model: Understanding Layout

Every HTML element is represented as a rectangular box. The CSS box model describes these boxes and their properties.

Components of the Box Model

Analogy: Think of the box model like a framed picture:

Box Model Properties

.box {
    /* Content dimensions */
    width: 300px;
    height: 200px;
    
    /* Padding (inner space) */
    padding-top: 20px;
    padding-right: 15px;
    padding-bottom: 20px;
    padding-left: 15px;
    /* Shorthand: padding: 20px 15px 20px 15px; */
    /* Further shorthand: padding: 20px 15px; (top/bottom right/left) */
    
    /* Border */
    border-width: 2px;
    border-style: solid;
    border-color: #333;
    /* Shorthand: border: 2px solid #333; */
    
    /* Margin (outer space) */
    margin-top: 30px;
    margin-right: 10px;
    margin-bottom: 30px;
    margin-left: 10px;
    /* Shorthand: margin: 30px 10px 30px 10px; */
    /* Further shorthand: margin: 30px 10px; (top/bottom right/left) */
}

Box-Sizing Property

By default, the width and height properties only set the size of the content area, not including padding or border. This can make layout calculations difficult.

The box-sizing property changes this behavior:

/* Default behavior */
.content-box {
    box-sizing: content-box;
    width: 300px;
    padding: 20px;
    border: 10px solid black;
    /* Total width: 300px + 40px padding + 20px border = 360px */
}

/* Alternative behavior */
.border-box {
    box-sizing: border-box;
    width: 300px;
    padding: 20px;
    border: 10px solid black;
    /* Total width: 300px (includes content, padding, and border) */
}

Modern practice: Many developers apply box-sizing: border-box; to all elements for more intuitive sizing:

* {
    box-sizing: border-box;
}

Real-world application: The box model is crucial for page layouts. Understanding it helps you create precise designs and troubleshoot spacing issues. For example, when creating a multi-column layout, you need to account for the full box size of each column (including margins, padding, and borders) to prevent unwanted wrapping or overflow.

Text Styling Fundamentals

Text is a primary component of most web pages. CSS offers extensive control over how text appears.

Typography Properties

Font Family

The font-family property specifies which font(s) to use.

body {
    font-family: 'Helvetica Neue', Arial, sans-serif;
}

List multiple fonts as fallbacks in case some aren't available. The browser will use the first available font in the list.

Font categories:

Font Size

The font-size property controls text size.

h1 {
    font-size: 32px;
}
p {
    font-size: 16px;
}

Size units:

Modern practice: Many developers set a base font size on the html element and use rem units elsewhere for scalable typography.

html {
    font-size: 16px; /* Base size */
}
h1 {
    font-size: 2rem; /* 2 × 16px = 32px */
}
.small-text {
    font-size: 0.875rem; /* 0.875 × 16px = 14px */
}
Font Weight

The font-weight property controls text thickness.

h1 {
    font-weight: bold; /* or 700 */
}
p {
    font-weight: normal; /* or 400 */
}
.light-text {
    font-weight: 300;
}

Values:

Text Alignment

The text-align property controls horizontal text alignment.

.center {
    text-align: center;
}
.right {
    text-align: right;
}
.justify {
    text-align: justify;
}
Line Height

The line-height property controls the vertical space between lines of text.

p {
    line-height: 1.6; /* 1.6 times the font size */
}
.tight {
    line-height: 1.2;
}
.spacious {
    line-height: 2;
}

Readability tip: Line heights between 1.4 and 1.6 are generally considered optimal for body text readability on screens.

Text Decoration

The text-decoration property adds or removes lines on text.

a {
    text-decoration: none; /* Removes underline from links */
}
.emphasis {
    text-decoration: underline;
}
.strike {
    text-decoration: line-through;
}
Text Transform

The text-transform property controls text capitalization.

.uppercase {
    text-transform: uppercase;
}
.capitalize {
    text-transform: capitalize; /* First letter of each word */
}
.lowercase {
    text-transform: lowercase;
}

Web Fonts: Beyond System Fonts

Web fonts allow you to use custom fonts not installed on users' computers.

Google Fonts Example
<!-- In HTML head -->
<head>
    <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
</head>

/* In CSS */
body {
    font-family: 'Roboto', sans-serif;
}

Real-world application: Typography is crucial for brand identity. Companies often use custom fonts across their digital and print materials for consistent brand recognition. For example, Netflix uses its custom "Netflix Sans" font across its platform.

Backgrounds and Borders

Backgrounds and borders are essential for creating visual divisions and interest in your layouts.

Background Properties

Background Color
.card {
    background-color: #f8f9fa;
}
Background Image
header {
    background-image: url('/images/header_bg.jpg');
    background-size: cover;
    background-position: center;
    background-repeat: no-repeat;
}

Background properties:

Background Shorthand
.hero {
    background: #333 url('/images/hero.jpg') center / cover no-repeat fixed;
}
Multiple Backgrounds
.layered {
    background: 
        linear-gradient(rgba(0,0,0,0.5), rgba(0,0,0,0.5)),
        url('/images/texture.jpg');
}

Border Properties

Basic Border
.box {
    border-width: 2px;
    border-style: solid;
    border-color: #333;
    
    /* Shorthand */
    border: 2px solid #333;
}
Border Styles

Common styles include: solid, dashed, dotted, double, groove, ridge, inset, outset.

.dashed-box {
    border: 2px dashed #999;
}
.dotted-box {
    border: 2px dotted #999;
}
Individual Border Sides
.custom-borders {
    border-top: 2px solid red;
    border-right: 3px dashed blue;
    border-bottom: 4px dotted green;
    border-left: 5px double orange;
}
Border Radius

Creates rounded corners.

.rounded {
    border-radius: 5px;
}
.circle {
    border-radius: 50%; /* Creates a circle if height = width */
}
.custom-shape {
    border-radius: 10px 20px 30px 40px; /* top-left, top-right, bottom-right, bottom-left */
}

Real-world application: Modern UI design often features subtle rounded corners (8-12px) on cards, buttons, and input fields to create a softer, more approachable look. Fully rounded elements (50% border-radius) are commonly used for profile pictures, notification badges, and action buttons.

Hands-On Exercise: Your First Styled Card

Let's apply what we've learned to create a simple styled card component.

HTML Structure

<div class="card">
    <img src="https://via.placeholder.com/300x200" alt="Card image">
    <div class="card_content">
        <h2 class="card_title">Card Title</h2>
        <p class="card_text">This is some sample text for our card component. It demonstrates how CSS can transform simple HTML into an attractive UI element.</p>
        <a href="#" class="card_button">Learn More</a>
    </div>
</div>

CSS Styling

/* styles/main.css */

/* Card container */
.card {
    width: 300px;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    overflow: hidden; /* Ensures the image doesn't break the rounded corners */
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.card:hover {
    transform: translateY(-5px);
    box-shadow: 0 5px 15px rgba(0,0,0,0.1);
}

/* Card image */
.card img {
    width: 100%;
    display: block;
}

/* Card content area */
.card_content {
    padding: 20px;
}

/* Card title */
.card_title {
    margin-top: 0;
    margin-bottom: 10px;
    color: #333;
    font-size: 20px;
}

/* Card text */
.card_text {
    color: #666;
    line-height: 1.5;
    margin-bottom: 20px;
}

/* Card button */
.card_button {
    display: inline-block;
    background-color: #0066cc;
    color: white;
    padding: 8px 16px;
    text-decoration: none;
    border-radius: 4px;
    font-weight: bold;
    transition: background-color 0.3s;
}

.card_button:hover {
    background-color: #0052a3;
}

Exercise explanation: This example demonstrates:

Try modifying this example by:

CSS Best Practices and Organization

As your CSS grows, organization becomes essential for maintainability.

Code Organization

Sample Organization

/* styles/main.css */

/* ==========================================================================
   Reset and base styles
   ========================================================================== */
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}

body {
    font-family: 'Roboto', sans-serif;
    line-height: 1.6;
    color: #333;
}

/* ==========================================================================
   Typography
   ========================================================================== */
h1, h2, h3, h4, h5, h6 {
    margin-bottom: 0.5em;
    font-weight: 500;
    line-height: 1.2;
}

p {
    margin-bottom: 1rem;
}

/* ==========================================================================
   Layout containers
   ========================================================================== */
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 15px;
}

/* ==========================================================================
   Header styles
   ========================================================================== */
header {
    background-color: #333;
    color: white;
    padding: 1rem 0;
}

/* ==========================================================================
   Navigation
   ========================================================================== */
nav {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

/* ==========================================================================
   Components: Buttons
   ========================================================================== */
.btn {
    display: inline-block;
    padding: 8px 16px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    font-weight: 500;
    text-decoration: none;
}

.btn-primary {
    background-color: #0066cc;
    color: white;
}

/* Add more component styles as needed */

Naming Conventions

BEM (Block Element Modifier) is a popular naming convention that creates clear, strict relationships between HTML and CSS.

<div class="card card--featured">
    <img class="card__image" src="image.jpg" alt="">
    <div class="card__content">
        <h2 class="card__title">Card Title</h2>
        <p class="card__text">Card description</p>
        <a href="#" class="card__button card__button--primary">Learn More</a>
    </div>
</div>

Real-world application: Large projects like Facebook, Airbnb, and Bootstrap use systematic CSS organization and naming conventions to manage thousands of style rules across hundreds of components. This approach allows multiple developers to work on the codebase without conflicts and makes future maintenance easier.

Debugging CSS

Troubleshooting CSS issues is a key skill for web developers.

Common CSS Problems and Solutions

1. Styles Not Applying

Possible causes:

Solution: Use browser dev tools to inspect the element and check which styles are being applied and which are being overridden.

2. Layout Breaking

Possible causes:

Solution: Temporarily add a background color or border to see the actual space elements are taking. Check box-sizing property.

3. Cross-Browser Issues

Possible causes:

Solution: Test in multiple browsers, use a CSS reset, and consider feature detection or polyfills for newer features.

Browser Developer Tools

Modern browsers include powerful tools for CSS debugging:

Pro tip: In Chrome DevTools, you can quickly test layout issues by toggling the "Show element margin" and "Show element padding" options in the Styles panel.

Further Resources and Next Steps

Documentation and References

Interactive Learning

CSS Tools

Topics to Explore Next

Today's Assignment: Style Your HTML Pages

Now it's your turn to apply what you've learned today.

Assignment Requirements:

  1. Create a new file called styles/my_styles.css
  2. Link it to your HTML pages from Monday's assignment
  3. Apply styling to the following elements:
    • Body (font-family, background color, text color)
    • Headings (colors, sizes, margins)
    • Links (colors, hover effects, text decoration)
    • Lists (spacing, bullet styles)
    • Create at least one card-like component with borders, padding, and hover effects
  4. Include at least 3 different CSS selectors (element, class, ID)
  5. Use the box model effectively (margins, padding, borders)
  6. Implement at least one hover effect
  7. Comment your CSS to explain what different sections do

Bonus challenges:

Submit your completed assignment by uploading both your HTML and CSS files to your course repository, maintaining the proper folder structure.

Wrapping Up

Congratulations! You've taken your first steps into the world of CSS. Today we covered fundamental concepts that will serve as building blocks for everything else you'll learn about web styling.

Remember:

In this afternoon's session, we'll dive deeper into CSS positioning, display properties, floats, and other layout techniques. The journey to mastering CSS is long, but with consistent practice, you'll develop the skills to create beautiful and responsive web designs.

Questions? Let's discuss them now before our break!