Using Global CSS When Styling in React
Let's say we have a React component App, which has a div, and inside the div there are three paragraphs:
function App() {
return (
<div>
<p>text</p>
<p>text</p>
<p>text</p>
</div>
);
}
Let's style this component. To do this, in the same folder src with our component, we will create a regular CSS file with styles styles.css for our tags.
In this file for the div we will create a class class1 with styles:
.class1 {
width: 200px;
border: 2px solid brown;
padding: 10px;
text-align: center;
}
Now let's add a class class2 with styles for the first paragraph:
.class2 {
color: orangered;
font-weight: bold;
}
Class class3 with styles for the second paragraph:
.class3 {
font-style: italic;
color: brown;
}
And finally, let's create a class class4 for the last paragraph:
.class4 {
background-color: orange;
font-weight: bold;
color: white;
}
We are done with the CSS file. All that remains is to apply our CSS styles that we wrote for the tags. Let's go back to our App.js file with the component.
The first thing we must do is add a line to the top of the file that imports our styles file styles.css:
import './styles.css';
Now, to apply CSS classes from the file to the component, we use the class attribute. For the first paragraph, we had the class2 class, let's apply it:
<p class="class2">text</p>
Similarly, we add classes for the remaining tags. As a result, we get the following code:
<div class="class1">
<p class="class2">text</p>
<p class="class3">text</p>
<p class="class4">text</p>
</div>
Create a React component that will contain a div, and in the div there will be two buttons. Create a file styles.css with CSS styles for your tags. Apply the written styles to the component tags.