Styling Components in React
Learn how to style React components using CSS stylesheets, inline styles, and best practices.
We'll cover the following...
Styling improves user interface and user experience both. It brings life to our components, making our application visually appealing and user-friendly. React supports various methods of styling, allowing us to choose the one that best fits our project’s needs.
Different ways to style components
In React, there are three ways to apply styles to our components.
Using CSS stylesheets
This is the traditional way of styling web pages, and it works seamlessly with React. Let's create a CSS file named styles.css in our project directory.
.header {background-color: #282c34;padding: 20px;color: white;text-align: center;}.paragraph {font-size: 18px;color: #333;}body {font-family: sans-serif;-webkit-font-smoothing: auto;-moz-font-smoothing: auto;-moz-osx-font-smoothing: grayscale;font-smoothing: auto;text-rendering: optimizeLegibility;font-smooth: always;-webkit-tap-highlight-color: transparent;-webkit-touch-callout: none;}h1 {font-size: 1.5rem;}
We can apply these styles using the className attribute. In JSX, className is used instead of class to avoid conflicts with the JavaScript class keyword.
In index.js:
Line 3: We import the
styles.cssfile so that the styles are applied globally. When we import the CSS file in our component, the styles become available to that component and any child ...