CSS Box Model

What is the CSS Box Model

Every element in CSS is a rectangular box. The CSS Box Model defines how the size of this box is calculated, including the content, padding, border, and margin. Understanding the Box Model is crucial for designing the layout of a web page, as it determines how elements are sized and spaced.

The four components of the Box Model are:

  1. Content: The actual content of the box (e.g., text or images).
  2. Padding: Space between the content and the border.
  3. Border: A line that surrounds the padding (if any) and the content.
  4. Margin: Space outside the border between this box and other elements.
scss




Tutorials dojo strip

Content Area

The content is where your text, images, or other elements live. This area can be sized using properties like width and height.

CSS

In this example, the div will have a width of 200 pixels and a height of 100 pixels. The content will fit inside this space.



Padding

The padding is the space between the content and the border of an element. You can control padding on all sides or individually for top, right, bottom, and left.

CSS

This adds 20 pixels of space around the content inside the div.

If you want to set padding for specific sides:

CSS

Or shorthand:

CSS




Border

The border goes around the padding and content. You can set the width, style, and color of the border.

CSS

In this example, the border is 2 pixels wide, solid, and black. You can also set borders individually for each side:

CSS




Margin

The margin is the space outside the border. It defines the distance between this element and neighboring elements. You can set margins just like padding:

CSS

Or specify margins for each side individually:

CSS

Shorthand for margins follows the same pattern as padding:

CSS




Box-Sizing Property

By default, the width and height of an element only apply to the content area. Padding and borders are added to that width and height, potentially making the element larger than expected. You can change this behavior using the box-sizing property.

CSS

With box-sizing: border-box, the padding and borders are included in the width and height, making layout calculations easier.




CSS Box Model Example Code

CSS




CSS Labs

Tutorials dojo strip