CSS Box Model

CSS box model represents the structure of an HTML element. In this box model, every element on a webpage is considered a rectangular box. Each rectangular box has a content area and optional padding, border, and margin areas.

Each of these rectangular boxes has a different set of properties that can be used to set or change its dimensions and can also interact with other boxes.

The following diagram demonstrate the box model:

Below is a quick explanation of all four areas the box model:

  • content – The area of the element where the actual text is placed.
  • padding – A transparent space between the content and the border of the element.
  • border – A surrounding of the element outside the padding area
  • margin – A transparent space around the element’s border area.

The example below demonstrate the CSS box model.

Example:

div{
   width: 300px;
   height: 200px;
   padding: 20px;
   border: 15px solid gold;
   margin: 20px;
}

Width and Height in CSS Box Model

In the last example, the div element has a width of 300px. But what width is it? Is it the width of the whole div element or just width of the content area?

Actually, When we set width or height of an HTML element, It is the width or height of the content area only. Margin, padding and border thickness are not included in it.

The full width and height of the element includes the padding, border and margin values. Their calculation is shown in the below table:

Box DimensionCalculation
Total Widthwidth + padding-left + padding-right + border-left + border-right + margin-left + margin-right
Total Heightheight + padding-top + padding-bottom + border-top + border-bottom + margin-top + margin-bottom

Example:

 div{
    width: 300px;
    height: 200px;
    padding: 30px;
    border: 20px solid gold;
    margin: 50px;
}

Total Width = 400px {300px(width) + 30px(padding) + 20px(border) + 50px(margin) }

Total Height = 300px { 200px(height) + 30px(padding) + 20px(border) + 50px(margin) }


Author

  • Manoj Kumar

    Hi, My name is Manoj Kumar. I am a full-stack developer with a passion for creating robust and efficient web applications. I have hands-on experience with a diverse set of technologies, including but not limited to HTML, CSS, JavaScript, TypeScript, Angular, Node.js, Express, React, and MongoDB.

Leave a Comment