I’m starting to learn CSS. I keep running into the same problem, however. How do I determine which Element gets property and value?
The majority of the time I get it right, but sometimes I try different Elements till I get the right one as I am not sure which Element to style. Thanks!
2
Answers
It’s not that complicated, use css selectors like
class
attribute which is the best option for styling most of the time, and then in you style sheet file , use the class name that you specified for the element and implement the style you want.In this way , you always know which element gets the style.
Additionally, study about css class naming method like BEM
Anatomy of CSS rules
CSS rules are mainly composed of two parts:
It is of the form of
We see that the ruleset is a set of rules, which are of the form of
<key>: <value>
;The selector
The selector determines what condition an element needs to meet in order to be affected by the ruleset attached to the selector.
Example:
Here, we have a rule for all
div
elements, specifying a border to any divs. We also have a rule specifically for the item whose id isidentifier
and another for items which have thesomeclass
class.These are the planword explanations of the selector.
Rule overrides
When you have multiple selectors met by the same element, if they have conflicting rules, then the priority score of the given selectors, which largely depends on their specificity determines which rule is to be applied.
Read more about specificity and priority of CSS selectors here: https://blogs.halodoc.io/best-practices-that-we-follow-to-avoid-specificity-issues/
In case of draws, that is, two different rules are of the same specificity, then the one which was defined later will override the one defined earlier:
You will also need to know about the
!important
keyword, which overrides the priority of rules:We see that the less specific rule is being applied because of the
!important
keywordRule inheritance
Some rules are inherited by descendants, but can be overriden lower down in the hierarchy:
We can see that the rule applied to
div
is inherited by its descendants, except for.exception
, which overrides it.Rules are reevaluated
If an element no longer meets a selector, then it loses the style. And, if an element becomes a match for a rule, then the rule is applied to it: