What are utility classes in CSS? Beginner CSS developer [closed]
You can use more specific names for your class, so if you want a specific padding
for example, you can have multiple options:
.block {
color: white;
background-color: teal;
margin: 10px;
}
.p-1 {
padding: 1rem;
}
.p-2 {
padding: 2rem;
}
.p-3 {
padding: 3rem;
}
@media only screen and (max-width: 600px) {
.p-1 {
padding: 1.5rem;
}
.p-2 {
padding: 2.5rem;
}
.p-3 {
padding: 3.5rem;
}
}
<div class="block p-1">Padding 1</div>
<div class="block p-2">Padding 2</div>
<div class="block p-3">Padding 3</div>
You can take a look at Tailwind CSS, for example.
There appears to be no formal definition of 'utility class'.
However, a common use of the phrase applies to simple, often single setting, classes with some semantics attached to the class name.
So in your examples perhaps a more 'utility' view would be to recognise that there may be several padding settings, for example and set the nomenclature accordingly.
.shadow-10-red {
box-shadow: 0 0 10px red;
}
.padding-10 {
padding: 10px;
}
.radius-10 {
border-radius: 10px;
}
.card-red {
background-color: red;
border:1px solid red;
}
However, these are utilities, very basic, and so are used rather differently from a normal class that sets several properties at once.
In the change of padding shown in the discussion on Charles Lavalard's answer, I worry that the p-1 class, which initially appears to have a link to the semantics - viz 1em, then gets changed to mean 1.5em. That isn't my understanding of a utility class.
But then perhaps it's all getting a bit subjective because utility classes don't have a standard definition. And perhaps the p-1, etc. in that example was not intended to have anything to do with the property values, but it was saying 'the first of the padding choices' which would be logical.