September 07, 2024

CSS Box Model


What is the CSS Box Model?


The CSS Box Model is a core concept in web development that defines how elements are structured and displayed on a webpage. Every HTML element is represented as a rectangular box, and the Box Model governs how these boxes are sized, spaced, and interact with other elements on the page. The model consists of four components that determine the overall size of an element:


  1. Content: The actual content inside the element, such as text, images, or media.
  2. Padding: The space between the content and the element’s border.
  3. Border: The line surrounding the padding and content.
  4. Margin: The space outside the border, separating the element from surrounding elements.



Components of the Box Model


1. Content


The content area contains the element's content (text, images, etc.). The width and height properties in CSS apply to this area by default.


div {
    width: 300px;
    height: 150px;
}


2. Padding


Padding is the space between the content and the border. You can set padding for all sides or for individual sides of the element.


div {
    padding: 10px;
}


To set padding for specific sides:


div {
    padding-top: 10px;
    padding-right: 15px;
    padding-bottom: 5px;
    padding-left: 20px;
}


3. Border

The border surrounds the padding and content. You can define the border’s width, style, and color.


div {
    border: 2px solid black;
}


To apply different borders for each side:


div {
    border-top: 2px solid black;
    border-right: 5px dashed blue;
}


4. Margin

The margin is the space outside the border, separating the element from other elements. Like padding, margins can be set for all sides or individually.


div {
    margin: 20px;
}


Individual margins:


div {
    margin-top: 10px;
    margin-bottom: 30px;
}



The Box Model in Action


Here’s an example combining all components of the Box Model:


div {
    width: 300px;
    height: 150px;
    padding: 20px;
    border: 5px solid black;
    margin: 15px;
}


  • Content: 300px wide, 150px tall.
  • Padding: 20px space inside the element, around the content.
  • Border: 5px solid black line around the padding.
  • Margin: 15px space outside the border.



The total width of the element includes content, padding, and border:


Total width = Content width (300px) + Padding (20px on both sides) + Border (5px on both sides) = 350px


Similarly, the total height is:


Total height = Content height (150px) + Padding (20px on both sides) + Border (5px on both sides) = 200px

CSS
box-model
Content
padding
border
margin