Generating Boxes with CSS

Objectives

After completing this lesson, you will be able to:

  • Use the box model to organize document elements on the page

The Box Model

At the heart of web design is the CSS box model, which outlines the rectangular boxes assigned to each document element. This model includes four essential components that determine not only the spatial arrangement of an element, but also its relationship to other elements on the page.

These components are content, padding, border, and margin.

  • Content: The content is the actual text, images, or other media contained within an element. The dimensions of the content area are determined by the element's width and height properties.

    Refer to the following code snippet.

    Code snippet
    div {
    width: 300px;
    height: 200px;
    }
    Expand
  • Padding: Padding is the space between the content and the border of an element. It provides breathing room for the content and can have different values for the top, right, bottom, and left sides. Padding is specified using the padding property and can be set individually using padding-top, padding-right, padding-bottom, and padding-left.

    Refer to the following code snippet.

    Code snippet
    div {
    padding: 10px 15px 10px 15px;
    }
    Expand
  • Border: The border is the outer edge of an element and surrounds the padding and content. It can have a style (solid, dashed, dotted, etc.), color, and width. Borders are specified using the border property and can be set individually for each side using border-top, border-right, border-bottom, and border-left.

    Refer to the following code snippet.

    Code snippet
    div {
    border: 2px solid black;
    }
    Expand
  • Margin: The margin is the space outside the border of an element, separating it from other elements on the page. Like padding, it can have different values for the top, right, bottom, and left sides. Margins are specified using the margin property and can be set individually using margin-top, margin-right, margin-bottom, and margin-left.

    Refer to the following code snippet.

    Code snippet
    div {
    margin: 20px 30px 20px 30px;
    }
    Expand

Visualizing the Box Model

To help visualize the Box Model, consider the following example of a <div> element with content, padding, border, and margin.

Refer to the following code snippet.

Code snippet
div {
width: 300px;
height: 200px;
padding: 10px 15px 10px 15px;
border: 2px solid black;
margin: 20px 30px 20px 30px;
}
Expand

A solid understanding of the CSS box model is essential for effective web page design and layout. By becoming familiar with the various components of the box model - content, padding, border, and margin - designers can create web pages with accuracy and aesthetic appeal.

Log in to track your progress & complete quizzes