Day 2 - CSS Box Model
The term "Box Model" is used when talking about design and layout. The CSS Box Model is essentially a box that wraps around every HTML element. It consists of: margins, borders, padding, and the actual content.
1. Padding (Space Inside)
Padding clears an area around the content (inside the border). It is affected by the background color of the element.
Code:
.pad-none {
padding: 0;
}
.pad-20 {
padding: 20px;
}
.pad-mixed {
padding: 10px 40px;
}
/* 10px top/bottom, 40px left/right */
Output:
2. Margin (Space Outside)
Margin clears an area outside the border. The margin is transparent.
Code:
.marg-20 {
margin: 20px;
}
.marg-auto {
margin: 0 auto;
/* Centers block elements horizontally */
width: 50%;
}
Output:
3. Border
A border goes around the padding and content.
Code:
.bord-solid {
border: 5px solid red;
}
.bord-dotted {
border: 5px dotted blue;
}
.bord-mixed {
border-top: 5px solid red;
border-bottom: 5px dashed green;
}
Output:
4. Border Radius
Used to round the corners of an element.
Code:
.rad-small {
border-radius: 5px;
}
.rad-large {
border-radius: 20px;
}
.rad-circle {
border-radius: 50%;
}
/* Makes a square a circle */
Output:
Circle
5. Box Sizing (Important!)
The box-sizing property allows you to include the
padding and border in an element's total width and height.
Code:
.content-box {
box-sizing: content-box;
/* Default */
width: 200px;
padding: 20px;
border: 10px solid blue;
}
/* Total Width = 200 + 40 (padding) + 20 (border) = 260px */
.border-box {
box-sizing: border-box;
/* Recommended */
width: 200px;
padding: 20px;
border: 10px solid blue;
}
/* Total Width = 200px (Content shrinks to fit) */
Output:
Width is 260px total.
Width is 200px total.