Chapter 3: CSS - The Style
If HTML is the skeleton of the internet, CSS (Cascading Style Sheets) is the skin, clothes, and makeup. It dictates everything visual: layout, colors, typography, and animations.
Writing CSS is easy. Writing maintainable and scalable CSS is incredibly difficult. Beginners often find themselves writing CSS that breaks uncontrollably when the browser window is resized. Let's fix that architecture.
The Box Model
The most fundamental concept in CSS is the Box Model. Every single element on a web page is a rectangular box. Understanding how this box is calculated will save you hours of debugging.
- Content: The actual text or image inside the box.
- Padding: Transparent space inside the box, pushing the content away from the borders.
- Border: The actual outline of the box.
- Margin: Transparent space outside the box, pushing other elements away.
/* The Pro-Tip every developer uses */
* {
box-sizing: border-box;
}
By default, adding padding increases the total width of your element. Applying box-sizing: border-box; to the universal selector (*) forces the browser to include padding and borders within the width you specify. Never start a project without this.
Flexbox vs CSS Grid
In the old days, developers used float to align elements, which caused endless layout bugs. Today, we have two layout engines natively built into CSS.
Flexbox (1-Dimensional Layout)
Use Flexbox when you want to lay out items in a single row OR a single column. It is perfect for Navigation bars, aligning icons with text, and centering content.
CSS Grid (2-Dimensional Layout)
Use Grid when you are building the macro-layout of a page. If you need a complex structure with rows AND columns (like a photo gallery, or a sidebar next to a main content area), CSS Grid is your weapon.
Architecture: Global Variables
Never hardcode hex colors throughout your CSS file. If you decide to change your primary brand color from red to blue, you will have to manually find and replace it 50 times. Use CSS Variables in the :root scope.
:root {
--primary-color: #e50914;
--background: #141414;
--text-main: #ffffff;
--spacing-md: 20px;
}
.button {
background-color: var(--primary-color);
padding: var(--spacing-md);
}
Responsive Design (Media Queries)
Never build a website that only looks good on your desktop monitor. You must use Media Queries to alter your CSS when the screen shrinks to mobile size. Always design for mobile FIRST, then scale up.
@media (min-width: 768px) { .container { width: 80%; } }
Mini Task: Flexbox Practice
- Create a
divwith a class of "container". - Put three smaller
divsinside it. - Write CSS to make the parent container
display: flex;and usejustify-content: space-between;to space them out perfectly.