He is a grouping. Whenever you have HTML elements that deserve to be grouped in a certain way, you can use a class to indicate that everyone has something in common. Of course, this only makes sense if you need to define styles and perform actions that must be executed in all class elements.
This is most useful for defining CSS for a group. In some cases for use in JS. In most cases the id
is more useful for JS since it usually works more with individualized elements.
You should ask yourself if there is any reason why certain elements on the page have the same behavior/style.
In fact, it makes no sense to create a class just by creating. It makes no sense, for example, to create a class equal to id
, as is often done without thinking. What some people recommend is to even create a class that is unique on the page, but then do not create a id
the same. Others prefer id
be used in this case to ensure that it will be unique.
A class can be used in multiple elements and it is possible to have multiple classes in the same element. It acts as a classification label (more or less with the tags that we have here, in forums, blogs, etc.).
Of course you can create the class in the HTML element without immediate use to provide a way that another developer can customize as you wish.
In the example shown I’m not really seeing a clear reason to create a class, but it might be necessary if it had more context.
Do not use where it is redundant. For example:
<div class="materia"> //aqui pode ser útil, depende do contexto
<h2 class="titulomateria"> //desnecessário aqui
I put in the Github for future reference.
In CSS just use .materia h2
, doesn’t need any name.
If you can’t justify why you’re using it, don’t use it. Obviously the justification needs to be coherent, it can’t be invented.
There is no defined rule, there is no way to say that it is right or wrong to use without the concrete case well contextualized, fits common sense. The context should define the need.
This can help.
In a very brief way, I understand that you should simply use class when you really need to. In the given example, it makes no sense, as you can make html { color... directly. On the other hand, if the CSS is external and the site is configurable, using PHP or another language "server side", you change the HTML class according to the context, instead of changing the CSS dynamically. In short, it depends on the common sense allied to the context. The most important thing is to know that there is no general rule to say what is right or wrong.
– Bacco