Web Fundamentals: CSS and the Box Model

Site Admin · 11 Sep 2026 · 5 views

Selectors and Rules

CSS, the Cascading Style Sheets language, controls presentation. A stylesheet is made of rules. Each rule has a selector that targets elements and a declaration block of property and value pairs. Selectors can be element names, classes, ids, or more complex patterns like descendants and pseudo-classes.

p {
    color: #333333;
    line-height: 1.6;
}

.highlight {
    background-color: #fff3cd;
}

The first rule styles every paragraph. The second one targets any element with class highlight. Class selectors are the workhorse of everyday CSS because they are reusable across many elements.

Box Model Basics

Every element is a rectangular box. From the inside out, a box has content, padding, border, and margin.

  • content - the text or image inside.
  • padding - space between content and border; part of the box.
  • border - the visible edge.
  • margin - space outside the border, pushing other boxes away.
.card {
    width: 300px;
    padding: 20px;
    border: 1px solid #cccccc;
    margin: 16px;
}

By default the width you set applies to the content area only, and padding and border add to it. That surprises many beginners. The fix is the universal rule box-sizing: border-box, which forces the width to include padding and border.

* {
    box-sizing: border-box;
}

After this rule, a 300px wide card stays 300px no matter how thick its padding becomes.

Display and Centering

The display property shapes layout flow. Block elements stack vertically, inline elements sit within a line of text, and flex and grid create modern layout systems. To center a block element horizontally, give it a fixed width and auto margins.

.centered {
    width: 600px;
    margin: 0 auto;
}

margin auto divides the remaining horizontal space between the two sides, landing the element in the middle.

Key Points

  • CSS rules pair a selector with property and value declarations.
  • Every box contains content, padding, border, and margin.
  • box-sizing border-box makes widths predictable.
  • display and margin auto control where boxes sit on the page.
Share this post:

Comments (0)

Please login or register to comment.