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:

/* CSS */
.pad-none {
    padding: 0;
}
.pad-20 {
    padding: 20px;
}
.pad-mixed {
    padding: 10px 40px;
}
/* 10px top/bottom, 40px left/right */

Output:

No Padding 20px Padding Mixed Padding

2. Margin (Space Outside)

Margin clears an area outside the border. The margin is transparent.

Code:

/* CSS */
.marg-20 {
    margin: 20px;
}

.marg-auto {
    margin: 0 auto;
    /* Centers block elements horizontally */
    width: 50%;
}

Output:

No Margin
I have 20px Margin
No Margin
I am centered with margin: auto

3. Border

A border goes around the padding and content.

Code:

/* CSS */
.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:

Solid Border
Dotted Border
Mixed Borders

4. Border Radius

Used to round the corners of an element.

Code:

/* CSS */
.rad-small {
    border-radius: 5px;
}
.rad-large {
    border-radius: 20px;
}
.rad-circle {
    border-radius: 50%;
}
/* Makes a square a circle */

Output:

Small Radius
Large Radius

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:

/* CSS */
.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:

content-box
Width is 260px total.
border-box
Width is 200px total.