CSS Box Model


🔹 What is the CSS Box Model?

Every HTML element can be considered as a box in CSS. The CSS Box Model describes how these boxes are rendered and how space is added around elements.

The box model consists of the following areas:

  1. Content – The actual text or image inside the element

  2. Padding – Space between the content and the border

  3. Border – The outline surrounding the padding

  4. Margin – Space outside the border, between this and other elements


🔸 Visual Representation:

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

🔸 Box Model Structure

div {
  width: 200px;
  padding: 10px;
  border: 5px solid black;
  margin: 20px;
}
  • Width applies only to the content.

  • Padding, border, and margin expand the element’s total space.


🔸 Total Width and Height Formula

Total width = content width + left/right padding + left/right border + left/right margin
Total height = content height + top/bottom padding + top/bottom border + top/bottom margin


🔸 Box-Sizing Property

To include padding and border in the width/height of the element:

* {
  box-sizing: border-box;
}

✅ This prevents layout issues and keeps the box size predictable.


Practice Questions

Q1. Create a <div> with 300px width and 20px padding.

Q2. Add a 5px solid red border around all paragraphs.

Q3. Set a 15px margin around a container div.

Q4. Write CSS to apply 10px padding and 5px margin to all headings.

Q5. Use the box-sizing property to include padding and border in the element’s width.

Q6. Write a rule that sets a 2px dotted green border for an image.

Q7. Apply 25px top and bottom margin and 10px left and right padding to a section.

Q8. Set different border styles for each side of a box (top, right, bottom, left).

Q9. Create a CSS class .box that has 10px padding, 3px border, and 15px margin.

Q10. Apply border-box sizing to all elements using the universal selector.


Go Back Top