Lesson 6: CSS Box Model, Margin, and Padding

In this lesson, we will explore the CSS box model, margin, and padding.

The CSS box model

The CSS box model is the foundation of layout and design in web development. It consists of four elements:

  • Content: The actual content inside the element, such as text or images
  • Padding: The space between the content and the border
  • Border: The border surrounding the padding and content
  • Margin: The space outside the border, separating the element from other elements

The total width and height of an element are determined by the sum of its content, padding, border, and margin.

Margin and padding

Margin and padding can be set using the following CSS properties:

  • margin: Sets the margin on all four sides of an element
  • margin-topmargin-rightmargin-bottommargin-left: Sets the margin on a specific side of an element
  • padding: Sets the padding on all four sides of an element
  • padding-toppadding-rightpadding-bottompadding-left: Sets the padding on a specific side of an element

You can use shorthand notation to set the margin or padding for multiple sides simultaneously:

/* Top and bottom margins are 10px, left and right margins are 20px */
margin: 10px 20px;

/* Top margin is 10px, right and left margins are 20px, bottom margin is 30px */
margin: 10px 20px 30px;

Border and outline

The border and outline can be set using the following CSS properties:

  • border: Sets the border width, style, and color on all four sides of an element
  • border-topborder-rightborder-bottomborder-left: Sets the border width, style, and color on a specific side of an element
  • border-widthborder-styleborder-color: Sets the border width, style, or color individually for all four sides of an element
  • outline: Sets the outline width, style, and color around an element

Example:

div {
  border: 2px solid black;
  outline: 1px dashed red;
}

Actionable Work

  1. Create an HTML file with various elements, such as divs, headings, and paragraphs.
  2. In a separate CSS file, experiment with applying different margin and padding values to the elements.
  3. Add borders and outlines to the elements, and observe how they interact with the margin and padding.
  4. Link your CSS file to your HTML file and preview your work in a web browser to see the effects of the box model, margin, padding, border, and outline on your layout.