Kaz
KPCKevin Powell - Community
•Created by Kaz on 4/14/2024 in #front-end
CSS Best Practices: classes vs target tag elements?
Hey everyone!
I have been wondering if 1) is it better to target html elements with their names on css or 2) preferably work with classes on them? Or 3) maybe a combination of the two?
I normally mix the two - add some classes on my html but mostly enjoy targeting the elements by their names. Especially now that css has nesting,
:nth-child(), :has()
, and other newer pseudo classes, etc. In addition, I also use CSS modules at work where (if I understand correctly) this encapsulates css to specific components/pages.
Say we have a hero component and the html looks like this:
<main class="hero">
<div class="hero__content">
<h1 class="hero__title">Lorem ipsum dolor sit amet.</h1>
<p class="hero__text"> Lorem ipsum dolor sit amet, consectetur adipiscing elit. </p>
</div>
</main>
In practice I could just target the whole component like so:
css
main {
width: min(90%, 1200px);
div {
padding: 1rem;
h1 {
color: white;
}
p {
color: gray;
}
}
}
Just some silly properties/styling. But the point is I could target them by using their tag names (main, div, h1, p) if I want to manipulate them instead of adding too many classes and overcrowding the html file.
Can someone please clarify this? maybe share some resources about good CSS practices? maybe check some real world projects that apply best practices?
Thanks a lot and would love to hear your thoughts!3 replies