Knowledge Base

Your essential guide to web development

CSS Fundamentals: Styling the Web

Cascading Style Sheets (CSS) is the cornerstone of modern web design. It allows you to control the presentation, layout, and visual appearance of your web pages, separating style from content (HTML). This article covers the fundamental concepts you need to get started with CSS.

What is CSS?

CSS works by selecting HTML elements and applying styles to them. These styles can include colors, fonts, spacing, positioning, and even animations. The 'cascading' aspect refers to how styles are applied when multiple rules conflict; a set of rules will be applied in a certain order, and the last rule in that order will win if it applies to the same property.

Selectors

Selectors are patterns used to select the HTML element(s) you want to style. Common selectors include:

Properties and Values

Once you've selected an element, you apply styles using properties and their corresponding values. A CSS rule consists of a selector followed by a declaration block enclosed in curly braces. Each declaration is a property-value pair, separated by a colon, and ends with a semicolon.

Example:

p { color: navy; font-size: 16px; margin-bottom: 1em; }

In this example:

The Box Model

Every HTML element can be thought of as a box. The CSS Box Model describes how these boxes are rendered on screen. It consists of:

You can control these dimensions using properties like width, height, padding, border, and margin.

Display Property

The display property determines how an element is rendered and how it interacts with other elements. Key values include:

How to Include CSS

There are three primary ways to include CSS in your HTML:

  1. Inline Styles: Using the style attribute directly on an HTML element. (Generally discouraged for maintainability).
    <p style="color: blue;">This text is blue.</p>
  2. Internal Stylesheets: Placing CSS rules within a <style> tag in the <head> section of your HTML document.
    <head> <style> h1 { color: green; } </style> </head>
  3. External Stylesheets: Linking to a separate .css file using the <link> tag in the <head>. This is the most recommended approach.
    <head> <link rel="stylesheet" href="styles.css"> </head>

Next Steps

Understanding selectors, the box model, and the display property are foundational. As you progress, explore concepts like positioning, floats, flexbox, CSS Grid, responsive design, transitions, and animations to create dynamic and visually appealing web experiences.

For more detailed information, check out the MDN Web Docs on CSS.