Type something to search...

CSS Box Model

CSS Box Model

The CSS box model is a fundamental concept that describes the structure of elements in a web page. It consists of four areas: content, padding, border, and margin.

Components of the Box Model

  1. Content:

    • The actual content of the element (e.g., text, images).
    • The size of the content can be controlled using width and height properties.
  2. Padding:

    • The space between the content and the border.
    • Controlled using the padding property.
  3. Border:

    • The edge surrounding the padding.
    • Controlled using the border property.
  4. Margin:

    • The space outside the border, separating the element from others.
    • Controlled using the margin property.

Example

div {
    width: 200px;
    height: 100px;
    padding: 10px;
    border: 2px solid black;
    margin: 20px;
}

Visual Representation

The box model can be visualized as follows:

+-----------------------+
|       Margin          |
|  +-----------------+  |
|  |     Border       |  |
|  |  +-----------+  |  |
|  |  |  Padding   |  |  |
|  |  |+---------+|  |  |
|  |  || Content ||  |  |
|  |  |+---------+|  |  |
|  |  +-----------+  |  |
|  +-----------------+  |
+-----------------------+

Box Sizing

The box-sizing property determines how the total size of an element is calculated.

  1. Content-Box (default):

    • The width and height include only the content.
    • Padding and border are added outside.
  2. Border-Box:

    • The width and height include content, padding, and border.

Example:

div {
    box-sizing: border-box;
}

Next: CSS Positioning →