CSS Box Model Tutorial

The Box model is a fundamental concept in CSS that defines the layout and dimensions of an element on a web page. It consists of four main components:

  1. Margins: The space around the element, outside of its border. This space can be used to separate the element from other elements on the page. The margin can be set using the margin property.

Example:

.box {
  margin: 10px; /* all four margins are set to 10px */
}
  1. Borders: The border is a line that goes around the element, between the margin and the padding. The border can be set using the border property.

Example:

.box {
  border: 2px solid black; /* 2px solid black border */
}
  1. Padding: The space between the border and the content of the element. The padding can be set using the padding property.

Example:

.box {
  padding: 20px; /* all four paddings are set to 20px */
}
  1. Content: The actual content of the element, such as text or images.

Here is an example of how these four components come together to create a box:

.box {
  width: 300px;
  height: 200px;
  margin: 10px;
  border: 2px solid black;
  padding: 20px;
}

In this example, the element with the class box will have a total width of 300px, a total height of 200px, a 10px margin around the outside, a 2px solid black border, and a 20px padding between the border and the content.

It's important to note that the width and height of an element only refer to the content area, not including the margin, border, or padding. If you want to set the overall width and height of an element, including these other components, you can use the box-sizing property to include them in the total width and height.

Example:

.box {
  width: 300px;
  height: 200px;
  margin: 10px;
  border: 2px solid black;
  padding: 20px;
  box-sizing: border-box; /* includes border and padding in width and height */
}

I hope this tutorial on the Box model in CSS has been helpful! Let me know if you have any questions.

That's it.

Did you find this article valuable?

Support Eirik Madland by becoming a sponsor. Any amount is appreciated!