I'm new to Web Development, and I have 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">
<article className='contact__option'>
{stuff here}
</article>
</div>
<div/>
My question is why we need to be specific and write both the container class and the contact__container class ? In the video he said he needs to be specific to be able to change the width, and yes when he adds the .container class it changes the width of elements. 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.
CodePudding user response:
It works both ways, but it is a good practice to write the two classes. It makes your code more readable and understandable.
CodePudding user response:
You can most definitely just define the class for contact__container alone.
Although, the way this is set up is to disallow that class styling from being applied anywhere outside of a 'container' class element.
As an example, in a setup similar to yours, 'bar' would receive styling:
<div >
<div >
I'm stylish!
</div>
</div>
But this 'bar' would ignore styling:
<div >
</div>
<div >
</div>
Check out my example here: Codepen
CodePudding user response:
In the example you shared .container
has some styles and container.contact__container
has extra styles.
This is saying apply the styles targeting .container
to ANY div which has a class of .container
, but ONLY apply the second set of styles to an element with the class of .container
if it ALSO has a class of .contact__container
.
So in the .contact__container
instance of .container
, do this extra stuff.
What's easy to miss as a beginner is how the the multiple classes are declared in the CSS.
If there is a gap between the declared classes:
.foo .bar {color: red}
It's saying make .bar
red only when it is a child of (is inside of) .foo
.
<div >
<div >
make me red
</div>
</div>
If there is NO gap between the declared classes:
.foo.bar {color: red}
It's saying make .bar
red only when it ALSO has a class of .foo
.
<div >
make me red
</div>