Introduction to Modern CSS

Cascading Style Sheets (CSS) transforms plain HTML documents into visually polished, responsive websites. It controls typography, color schemes, spacing, grid layouts, animations, and adaptive designs across phones, tablets, and desktop displays.


CSS Rule Syntax & Selector Specificity

A CSS rule consists of a selector and a declaration block:

css
/* Selector { Property: Value; } */
.card-title {
  color: #193D35;
  font-size: 1.25rem;
  font-weight: 700;
  margin-bottom: 0.5rem;
}

The Specificity Hierarchy

When multiple conflicting rules target the same element, browsers calculate specificity:

  1. Inline Styles: (e.g. style="color: red;") → Weight: 1000
  2. ID Selectors: (e.g. #main-header) → Weight: 100
  3. Class, Attribute, and Pseudo-class Selectors: (e.g. .btn, [type="text"], :hover) → Weight: 10
  4. Element and Pseudo-element Selectors: (e.g. h1, p, ::before) → Weight: 1

Mastering the CSS Box Model

Every element on a webpage is treated as a rectangular box. The Box Model consists of 4 concentric layers:

  1. Content: The actual text, image, or video.
  2. Padding: Transparent inner space between content and the border.
  3. Border: Line framing the padding and content.
  4. Margin: Outer transparent space separating the element from neighbors.
css
/* Best Practice Reset */
*, *::before, *::after {
  box-sizing: border-box;
}

.box {
  width: 300px;
  padding: 20px;
  border: 2px solid #E2D0A6;
  margin: 16px auto;
}

Pro Tip: box-sizing: border-box ensures that padding and borders are included inside the defined width rather than expanding it.


Flexbox vs. CSS Grid: When to Use Which?

Modern layouts rely on Flexbox and Grid rather than old float hacks:

1. Flexbox (One-Dimensional Alignment)

Ideal for aligning elements along a single axis (either row or column), such as navigation bars, button groups, and centered cards:

css
.navbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 1rem;
}

2. CSS Grid (Two-Dimensional Layouts)

Ideal for managing rows and columns simultaneously, such as photo galleries, dashboard widgets, and multi-column article grids:

css
.card-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 1.5rem;
}

Frequently Asked Questions

What is the difference between em and rem units?

rem is relative to the root <html> element's font size (typically 16px by default), making it predictable and consistent. em is relative to the font size of its immediate parent element, which can compound in nested structures.

What are CSS Custom Properties (Variables)?

Custom properties allow you to declare reusable values once and apply them everywhere:

css
:root {
  --primary-color: #193D35;
}
.btn {
  background-color: var(--primary-color);
}

Practice Your CSS Skills