Introduction to CSS
Master CSS fundamentals for styling web pages.
By EMEPublished: February 20, 2025
cssstylingselectorsbox modelresponsive design
A Simple Analogy
CSS is like clothes for HTML. HTML is the body, CSS makes it look beautiful and organized.
Why CSS?
- Styling: Make pages beautiful
- Consistency: Reuse styles across pages
- Maintainability: Change styles in one place
- Responsive: Works on all devices
- Animation: Add movement and interaction
CSS Selectors
/* Element selector */
p { color: blue; }
/* Class selector */
.highlight { background-color: yellow; }
/* ID selector */
#main { width: 100%; }
/* Attribute selector */
input[type="text"] { border: 1px solid gray; }
/* Combinators */
div > p { margin: 10px; } /* Direct child */
div p { color: red; } /* Descendant */
div + p { margin-top: 20px; } /* Adjacent sibling */
The Box Model
Content -> Padding -> Border -> Margin
┌─────────────────────────┐
│ Margin │
│ ┌───────────────────┐ │
│ │ Border │ │
│ │ ┌───────────────┐ │ │
│ │ │ Padding │ │ │
│ │ │ ┌───────────┐ │ │ │
│ │ │ │ Content │ │ │ │
│ │ │ └───────────┘ │ │ │
│ │ └───────────────┘ │ │
│ └───────────────────┘ │
└─────────────────────────┘
div {
content: 200px;
padding: 20px; /* Inside border */
border: 2px solid;
margin: 10px; /* Outside border */
}
/* Shorthand */
margin: 10px 20px; /* vertical horizontal */
padding: 10px 20px 30px 40px; /* top right bottom left */
Flexbox Layout
.container {
display: flex;
justify-content: space-between; /* Horizontal alignment */
align-items: center; /* Vertical alignment */
gap: 20px; /* Space between items */
}
.item {
flex: 1; /* Equal width */
flex-basis: 200px; /* Base size */
}
Grid Layout
.grid {
display: grid;
grid-template-columns: 1fr 2fr 1fr; /* 3 columns */
grid-template-rows: auto 1fr auto; /* 3 rows */
gap: 20px;
}
.item {
grid-column: 1 / 3; /* Span 2 columns */
grid-row: 2; /* Row 2 */
}
Responsive Design
/* Mobile first */
body {
font-size: 14px;
}
/* Tablet */
@media (min-width: 768px) {
body {
font-size: 16px;
}
}
/* Desktop */
@media (min-width: 1024px) {
body {
font-size: 18px;
}
}
Best Practices
- Mobile first: Start small, enhance
- Semantic HTML: Use proper elements
- Use variables:
--color-primary: blue; - Minimize specificity: Avoid deep nesting
- Test responsiveness: Check all devices
Related Concepts
- CSS Preprocessors (Sass, Less)
- CSS-in-JS (Styled Components)
- Tailwind CSS
- Bootstrap framework
Summary
CSS controls presentation of web pages. Master selectors, box model, flexbox, and grid to build responsive, maintainable designs.