CSS Box Model - Detailed Overview

Introduction to the CSS Box Model

The CSS Box Model describes how the elements on a web page are structured and laid out. It consists of the following components:

Box Model Example

Here is a visual representation of the CSS Box Model:

div {
    width: 200px;
    height: 100px;
    padding: 20px;
    border: 5px solid #333;
    margin: 15px;
    background-color: #e0e0e0;
}
Content Area

Understanding Padding

The padding property creates space between the content and the border. For example:

div {
    padding: 20px;
    border: 1px solid #ddd;
    background-color: #f4f4f4;
}
Padding: 20px

Understanding Border

The border property adds a border around the padding and content. For example:

div {
    border: 3px solid #333;
    background-color: #f4f4f4;
}
Border: 3px solid #333

Understanding Margin

The margin property creates space outside the border. For example:

div {
    margin: 15px;
    border: 1px solid #ddd;
    background-color: #f4f4f4;
}
Margin: 15px

Box Model with Flexbox

Flexbox layout can affect how the box model properties are applied. For example:

.container {
    display: flex;
    justify-content: space-around;
}

.box {
    width: 100px;
    height: 100px;
    padding: 10px;
    border: 2px solid #333;
    background-color: #e0e0e0;
}
Flexbox Box
Flexbox Box