Styling with CSS
- React course
- Beginner
- Lesson 53/84
- 4 min
Learn to style with className from an external CSS file.
Styling with CSS
The simplest styling method in React is using an external CSS file with className. In JSX you write className, not class.
Example: <button className="btn">Save</button>. A CSS rule .btn { color: blue; } paints this button.
You import the CSS file into JSX; Vite/Webpack loads it automatically. This method is familiar and works in big projects.
Importing a CSS file
You import the CSS file at the top of the component file: import "./Button.css". The bundler adds it to the page automatically.
With this method styles are global; if two components use the same class name they clash. This is why CSS Modules or scoped solutions are preferred.
For now we learn the simplest method; Modules come later.
Practice Styled button
Complete the skeleton. Write a SaveButton component that returns <button className="btn">Save</button>. Export it.
Starter code
// Define SaveButton hereSample solution
function SaveButton() {
return <button className="btn">Save</button>;
}
export default SaveButton;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Which attribute is used for styling class in JSX?
class is a reserved word in JavaScript.- style
- class
- className Correct answer
- css
Explanation: React uses className instead of class.
2 Styling with CSS: fill in the missing part
<button className="____">Save</button>
<button className="btn">Save</button>
Explanation: You styled with className btn.
3 Styling with CSS: match the terms
| Term | Meaning |
|---|---|
className |
Style class |
import "./x.css" |
Load CSS |
.btn |
CSS selector |
global |
Clash risk |