Learn CSS Basics
CSS (Cascading Style Sheets) controls how your HTML looks. Explore key concepts below!
1. Adding CSS
Use <style>
in the head, external files, or inline styles.
link
and press Tab (Mac: Tab, Windows: Tab) to auto-generate a stylesheet link.
2. Colors
Change text and background colors with properties like color
and background-color
.
Try it: Click to toggle colors!
3. Fonts
Control text appearance with font-family
, font-size
, and font-weight
.
Try it: Click to toggle font!
4. Box Model
Every element is a box with margin
, padding
, border
, and content.
Try it: Click to toggle box model!
5. Selectors
Target elements with tag, class (.
), or ID (#
) selectors.
6. Positioning
Control layout with position
(static, relative, absolute, fixed).
Best Practices and CSS Variables
Writing clean, maintainable CSS is key. Here’s how to do it:
Best Practices
- Use Meaningful Names: Classes like
.button
are better than.btn1
. - Keep it DRY: Don’t Repeat Yourself—reuse styles with classes or variables.
- Organize Files: Separate CSS into logical files (e.g.,
layout.css
,theme.css
). - Use Comments: Explain complex styles with
/* comments */
. - Minimize Specificity: Avoid overusing IDs or deep nesting (e.g.,
#main .section p
).
CSS Variables (Custom Properties)
Variables make styles easy to update globally. Define them in :root
for global scope.
Why Use Variables?
- Consistency: Change one value, update everywhere.
- Theming: Easily switch between light/dark modes (like this site!).
- Readability: Names like
--main-color
are self-explanatory.
Try it: This site uses variables! Check styles.css
to see them in action.