I'm new to Web Development, and i've made a good progress so far.
I've encountered this in a recent CSS tutorial while building my Portfolio:
.container {
width: var(--container-width-lg);
margin: 0 auto;
}
.container.contact__container {
width: 50%;
display: grid;
grid-template-columns: 50% 50%;
gap: 12rem;
}
I have the .container Class in the main index.css file, which has width and margin as properties that's it. But in my Contact component, in contact.jsx I have one div element with the classes contact__container and container, and it's only div that has the contact__container! :
<div className="container contact__container">
<div className="contact__options">
{stuff here}
</div>
<form>
{Stuff here}
</form>
</div>
My question is why we need to be specefic and write both the container class and the contact__container class ? In the video he said he needs to be specefic to be able to change the width, but what does that mean please? why I can't just do:
.contact__container {
width: 50%;
display: grid;
grid-template-columns: 50% 50%;
gap: 12rem;
}
Thanks a bunch
Top comments (4)
As @alohci mentions, with just this bit of CSS, it's not strictly necessary - but that's purely because of the order of the CSS declarations. Were you to swap them around, it could already result in different rendering, if you were to omit the
.container
.I would recommend reading into CSS specificity and cascading rules, which may explain what the reasoning here is. (And then not reading too much further, because we have three different ruling religions about what makes "good" CSS right now, each of which recommends a very different approach to how much specificity is needed...)
In the exact example you've given, you probably can. But if you just use
.contact__container
as your selector, you're relying on DOM ordering to ensure that it overrides the.container
rule, which can be fragile in some contexts. By using.container.contact__container
you're using a higher specificity selector and guaranteeing that it will override the.container
rule.thank you, still a little bit confused, but i'll do more research based on what you mentioned, thanks man!
Check out my profile, I've some posts about CSS, you can find this one linked below specially useful. Here you can find an extense explanation on how CSS handles priorities and how you can handle specificity.
Complete CSS Guide for beginners and not so beginners
JoelBonetR ・ Jun 23 '20 ・ 30 min read
Hope it helps 😁