Why do we need to use a CSS Class?

Why do we need to use the <style> ... </style> to change the color of multiple elements while we can just use the code class=“red-text” in each element? The CSS class just give us an extra step but actually it is not different from using the class=“red-text”…

Please explain for me…
Many thanks

I’m fairly new to coding, but my understanding is that by using CSS you can apply multiple styles to an element or any number of elements by defining the attributes in a CSS class and so not have to have a long list of class definitions in the html.

I find that this makes my code easier to read (by read i actually mean fix when it doesn’t do what I expect) and also keeps styling seperate and easier to find should i chnage my mind later about what i want it to look like. For ecample, if i’ve defined and applied a class in more than one place, then i only have to amend it once in the CSS and not in several places in the HTML.

For short challenges where you don’t need to apply a style more than once it probably won’t matter so much in terms of the end result, but as challenges become more complex seperating your styling will be a god send so it’s a good habit to get into I believe.

I hope that helps

I’m not entirely sure what you’re asking since you’ve just suggested we use CSS classes instead of CSS classes. What I think you meant is, Why do we use CSS classes when we can just write our styles inline with the element?

<style>
    .red-text {
       color: red;
    }
</style>

<!-- some HTML... -->
<p class="red-text">This is red</p>

<!-- writing inline -->
<p style="color: blue;">This is blue</p>

So why do we use classes? There are two big reasons.

  1. CSS gets very complicated. Here’s an example from my personal site. This style code covers only one section of my page, and it’s just a simple, static site. Writing all of that inline would be both an eyesore and difficult to change. Keeping CSS in a separate file fixes these problems.

  2. Separating CSS and HTML allows us to share code. Libraries like Bootstrap make webpage creation simpler because you can use a bunch of pre-written styles. This would not be possible if all styles were written inline.