Should my stylesheet definitions mirror the DOM hierarchy? If I have:
<div id="container">
<div class="item">
<div class="property">
<span id="1243"></span>
</div>
</div>
</div>
When I want to style each property, should I just say:
.property { color: red; }
Or should I do
#container .item .property { color: red;}
I've used both. I like the first for brevity and because I do not need to update it if the hierarchy changes, but the second helps me read the CSS.
The !important rule in CSS is used to add more importance to a property/value than normal. In fact, if you use the !important rule, it will override ALL previous styling rules for that specific property on that element!
CSS Order Matters In CSS, the order in which we specify our rules matters. If a rule from the same style sheet, with the same level of specificity exists, the rule that is declared last in the CSS document will be the one that is applied.
The class selector is useful for targeting multiple elements, things like cards or images that you want to have matching styles. To select an element with a specific class, you use a . character (period) and then follow it with the class name. Let's look a CSS selector example for the class selector.
As with any code (or any writing), you should write it to express your intended meaning as clearly and accurately as possible.
So, if you want any element with a class of property
that’s a descendant of an element with class of item
which itself is a descendant of an element with an id of container
to have these styles, then write #container .item .property
.
If you want an element with a class of property
to have these styles regardless of what it’s a descendant of, then write .property
. This is appropriate for classes that you want to use in a lot of different places on the site; e.g. button styles.
One thing I would note is that every CSS selector you add increases the specificity of the selector, i.e. #container .item .property
is more specific than .property
. So styles applied with #container .item .property
will require a selector of greater specificity to override them if you want to later, forcing you to write this longer selector out again. But I think that’s a secondary concern compared to writing what you mean.
This is completely up to you, you don't need to use the full path in css, but using a full path can be usefull when you have 2 div's with the same class but different parents and you want to style them both differently.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With