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!
2 Replies
EIO
EIO9mo ago
Generally, it's best to use classes. Here are my reasons: 1. There's every chance that as you go on with your project, you would want different elements which are of the same tag name to have different css rules applied to them. You'd get stranded if you started off with tag names. 2. Tag names are not flexible enough to absolutely manage the complexity of specificity. Of course, there are times where it makes sense; like css resets. When writing vanilla css, you can go the BEM way, use utility classes or just go random (this will hinder scaling though) Or you can use frameworks like Tailwind (utility first), Bootstrap; Css in Js options like PandaCss
BEM — Block Element Modifier
BEM — Block Element Modifier is a methodology, that helps you to achieve reusable components and code sharing in the front-end.
reddogg476
reddogg4769mo ago
There are many configurations, that's the fun of classes. React use IDs for components. In component CSS, make the largest possible container be an ID, then use classes across the components or within the component. Or, have a class decide the component, and use IDs selectively to make an element unique on a page. Or target elements, but, like eioluseyi says, tag names are not great because reusing a tag will also apply the CSS to it.
Want results from more Discord servers?
Add your server