Contenido del Curso
React Mastery
React Mastery
Styling with the CSS File
Using a CSS file to style React components originates from the traditional HTML-CSS structure. Here is a step-by-step guide on how we can utilize a CSS file to style React components:
1. Create a CSS File
To begin, create a separate CSS file with the .css
extension. This file can be located in the same folder as the component or in a dedicated folder specifically for styles, where all CSS files are organized together.
Example:
2. Import the CSS File
Use the' import' statement to import CSS files into the component file. Place this import statement at the top of the component file. Inside the quotation marks ''
, specify the appropriate file path.
Example:
If the CSS file is in the styles
folder, then the import statement would have the following syntax:
Note
Use the dot and slash notation
./
to reference a file within the same directory. To access a file outside the current folder and navigate to the parent directory, use two dots and a slash../
.
3. Apply Styles to the Component
Once the styles have been imported, your component becomes aware of the presence of the CSS. Consequently, you can employ CSS selectors and class names to style the elements. The only distinction is that, in React applications, we utilize the className
attribute instead of the class
attribute used in HTML files.
Example:
Now we can use the CSS classes container
, title
, and description
to style the elements within the Block
component.
Add styling
At this point, we can open the CSS file and apply styles to the defined class names. For instance, the index.css
file may contain the following styles:
Following these steps, we will apply the styles defined in the CSS file to the corresponding elements in the React component.
Full app code:
¡Gracias por tus comentarios!