If you followed this course from the beginning, you may have noticed that we used two different approaches when it comes to writing CSS code.
For example, if you want to create a card component with an image, a title, and a short description, this is what you can do:
1<div class="container">
2 <div class="card">
3 <img class="image" src="https://images.unsplash.com/. . ." alt="" />
4 <h2 class="title">
5 Lorem ipsum dolor sit amet consectetur adipisicing elit
6 </h2>
7 <p class="description">
8 Lorem ipsum dolor sit amet consectetur adipisicing elit. . .
9 </p>
10 </div>
11
12 . . .
13</div>
1.container {
2 display: flex;
3 flex-direction: row;
4 gap: 10px;
5}
6
7.card {
8 width: 400px;
9 height: fit-content;
10
11 display: flex;
12 flex-direction: column;
13 gap: 10px;
14
15 border: solid 2px;
16 border-radius: 10px;
17
18 margin: 10px;
19 padding: 10px;
20}
21
22.image {
23 width: 100%;
24 border-radius: 10px;
25}
26
27.title {
28 font-family: "Courier New", Courier, monospace;
29 font-size: 1.5rem;
30 font-weight: 700;
31}
32
33.description {
34 font-family: "Courier New", Courier, monospace;
35 font-size: 1rem;
36 font-weight: 500;
37}
In this example, the class names describe the purpose of the element.
However, notice that the CSS file contains many repetitions. For example, there are two gap
s and two font-family
s with the same values.
This might not be a good approach for a large-scale project. Image your website needs a different card component with only a different border color. You'll have to recreate the entire .card
block with only a different border
property.
Eventually, your CSS file will become impossible to maintain. A better solution is to go with a more atomic approach, meaning each CSS block only deals with one specific style. For example:
1<div class="flex flex-row gap">
2 <div class="flex flex-col gap border border-radius-lg padding">
3 <img class="w-full" src="https://images.unsplash.com/. . ." alt="image" />
4 <h2 class="font-mono font-lg">
5 Lorem ipsum dolor sit amet consectetur adipisicing elit
6 </h2>
7 <p class="font-mono font-sm">
8 Lorem ipsum dolor sit amet consectetur adipisicing elit. . .
9 </p>
10 </div>
11
12 . . .
13</div>