CSS Stylesheets and Global Class Names
CSS Stylesheets and Global Class Names
1. Traditional CSS in Modern React
The simplest way to style React components is writing standard CSS in external .css files and importing them directly into your JavaScript files.
When you import a stylesheet via Vite or Webpack:
The bundler extracts the CSS, injects it into a <style> tag in development, and bundles it into an optimized, minified .css file in production.
2. Using Global Class Names
Once imported, you apply styles using the className attribute:
3. The Major Danger: Global Scope Collisions
While importing plain CSS files into components feels modular, standard imported CSS files are completely global!
Importing import './cards.css' inside CourseCard.jsx does not restrict the .card-title class to CourseCard. If another developer creates UserProfile.jsx and imports profile.css with a .card-title class, both rules conflict globally across the entire application:
4. Best Practices for Plain CSS in React
If using traditional CSS stylesheets without CSS Modules or Tailwind:
- Follow BEM (Block-Element-Modifier): Use strict naming prefixes like
.msk-course-card,.msk-course-card__title,.msk-course-card--highlightedto prevent global name clashes. - Global Design Tokens in
index.css: Place CSS variables (:root { --primary-color: #0284c7; }), base resets, and typography inindex.css. - Prefer CSS Modules or Tailwind CSS for Enterprise Apps: Use modern scoped tools to eliminate global namespace collisions entirely.
Practice Quiz
:hover and media queries?CSS Modules for Scoped Component Styling
Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
Related Lessons
| Previous Lesson | Next Lesson |
|---|---|
| Inline Styles and Style Objects | CSS Modules for Scoped Component Styling |
Practice Quiz
Test your understanding of this lesson with 5 questions. Each question has one correct answer.