Overview
The CSS box model is a method for visualizing the layout of every HTML element, which consists of the content, padding, borders, and margin.
- Content – the body of the HTML element (text, images, form, etc.)
- Padding – a transparent area surrounding the element that gives it space which is most notable when a border is applied
- Border – a colored (can be transparent) line drawn around the content and padding (think of it as the outline you color within in a coloring book)
- Margin – an area outside the element that gives it space from other surrounding elements
The padding and margin are transparent and are just there to give your element room to breath so that it isn’t squashed up against its own border (padding) or other elements (margin).
Note
The image above shows where outline fits in. But the outline is NOT calculated into the size of the element and may actually overlap the margin, or if there’s no margin, other elements next to it.
Determining the Width and Height of an Element
div {
width: 500px;
height: 300px;
padding: 20px;
border: #ff0000 solid 2px;
margin: 50px;
}
Width:
- Total width = width + left padding + right padding + left border + right border + left margin + right margin
500px (width)
+ 40px (left + right padding)
+ 4px (left + right border)
+ 100px (left + right margin)
= 644px
Height:
- Total height = height + top padding + bottom padding + top border + bottom border + top margin + bottom margin
300px (width)
+ 40px (top + bottom padding)
+ 4px (top + bottom border)
+ 100px (top + bottom margin)
= 444px
box-sizing Property
The box-sizing property can be used to alter how the the width and height are calculated.
CSS Notes:
- The “inherit”, “initial” and “unset” keywords can be used with any CSS property to set its value
- In CSS there are many ways to express a color value in a property
We’d like to acknowledge that we learned a great deal of our coding from W3Schools and TutorialsPoint, borrowing heavily from their teaching process and excellent code examples. We highly recommend both sites to deepen your experience, and further your coding journey. We’re just hitting the basics here at 1SMARTchicken.