Understanding CSS

CSS (Cascading Style Sheets) is the language used to describe the presentation of an HTML document. While HTML defines what content exists, CSS determines how that content looks — its colors, sizes, spacing, typography, animations, and responsive layout.

💡 Key Concept: The "cascading" in CSS means styles can be inherited, overridden, and layered from multiple sources. Specificity and order determine which styles win.

How CSS Works

CSS uses selectors to target HTML elements and declarations to set property values. A declaration is a property-value pair like color: blue;.

/* Selector { Property: Value; } */
h1 {
  color: #1d4ed8;
  font-size: 2.5rem;
  margin-bottom: 16px;
}

.card {
  background: white;
  border-radius: 12px;
  padding: 24px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

Three Ways to Add CSS

  1. Inline — Directly on an element: <p style="color: red;">
  2. Internal — Inside a <style> tag in the <head>
  3. External — In a separate .css file linked with <link> (recommended)

Essential CSS Properties

  • color / background — Text and background colors
  • font-size / font-weight / font-family — Typography
  • margin / padding — Spacing outside and inside elements
  • border / border-radius — Borders and rounded corners
  • display — Block, inline, flex, grid layout modes
  • position — Static, relative, absolute, fixed, sticky
  • transition / animation — Smooth visual effects
  • @media — Responsive breakpoints for different screen sizes

Modern Layout: Flexbox & Grid

Flexbox arranges items in a single row or column with automatic alignment. CSS Grid creates two-dimensional layouts with rows and columns. Together they handle nearly every layout challenge.

/* Flexbox Example */
.flex-container {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 16px;
}

/* Grid Example */
.grid-container {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 20px;
}

🧪 Try It Yourself — Live CSS Visualizer

Adjust the controls below and watch the box transform in real time:

CSS Box

Best Practices

  • Use external stylesheets for separation of concerns
  • Use CSS custom properties (--variables) for theming
  • Design mobile-first with min-width media queries
  • Minimize use of !important — fix specificity issues instead
  • Use Flexbox for one-dimensional and Grid for two-dimensional layouts