Concept Explanation
Refactoring in CSS means improving structure without changing the visual result. In this lesson, you will take a small set of repeated rules and reorganize them into cleaner, easier-to-maintain styles. The goal is to notice when declarations belong in a shared utility, when a component deserves its own selector, and how custom properties can reduce duplication. By the end, you should be able to look at a messy stylesheet and turn it into something more consistent, readable, and safer to extend.
Where to Put the Code
- Start with variables and inputs. Place style rules in reusable class selectors.
- Add processing logic in the middle section.
- Finish with output and quick validation.
Command Reference
- Start by finding declarations that appear more than once and group them intentionally.
- Move repeated spacing, border, or color values into custom properties when they clearly belong together.
- Check the page before and after refactoring to confirm the design still looks the same.
- Write down one reason your updated selectors are easier to maintain than the original version.
Step-by-step Guide
- Read the starter CSS and mark any repeated values or repeated selector patterns.
- Choose one refactor first, such as merging duplicate card styles or extracting a shared variable.
- Run the page again and confirm that the visual result did not accidentally change.
- Review the new structure and decide whether the selector names still make sense to someone else reading the file.
- Finish with a short checklist: less repetition, clearer naming, same output.
Practice Exercises
- Refactor a button stylesheet that repeats the same padding, border radius, and font rules in three classes.
- Take a group of alert styles and extract shared rules while keeping success and error variants separate.
- Rewrite a small stylesheet so spacing values come from variables instead of hard-coded numbers.
Coding Challenges
- Create two valid refactors for the same stylesheet and compare which one is easier to extend later.
- Refactor a component without increasing selector specificity or making overrides harder.
Mini Practice Tasks
- Rename one selector so its purpose is clearer at a glance.
- Extract one repeated value into a custom property.
- Summarize the main benefit of your refactor in one sentence.
Common Mistake
Skipping input validation or mixing logic/output in one unstructured block.
Real-life Mini Challenge
Build a small real-life example for this lesson topic using 3 clear steps: input, process, output.