I've been reading about CSS and I am really confused about how the inheritance works (I think thats the right term for the following). In CSS I can declare a class:
#mytext {
}
then I see some people do:
p.mytext {
}
But why do that? Why can't they just do:
<p class="mytext">
Without declaring p.mytext
? Does it make sense what I am asking?
and sometimes i see:
p#mytext
... Why is it different? I'll keep searching tutorials but thanks for any advise.
In CSS, inheritance controls what happens when no value is specified for a property on an element. CSS properties can be categorized in two types: inherited properties, which by default are set to the computed value of the parent element.
Each property may also have a cascaded value of 'inherit', which means that, for a given element, the property takes as specified value the computed value of the element's parent. The 'inherit' value can be used to enforce inheritance of values, and it can also be used on properties that are not normally inherited.
The pound sign (#
) refers to an ID which needs to be unique for the page. The period (.
) refers to a class which can be used many times. People would use p#mytext
if they wanted a unique styling for one (just one) paragraph tag.
You can read up about it here.
Wanted to add that some web developers seem to gravitate towards declaring everything as classes. If you use a layout generator of any kind more often than not every element will be a class.
#mytext
references <p id="mytext"/>
(doesn't need to be a p
element, #mytext
just refers to that ID)
Whereas .mytext
references <p class="mytext"/>
(doesn't need to be p
element, .mytext
just refers to anything with that classname)
By adding other things such as p.mytext
you create a stronger bind to your rule, for instance:
p.mytext { color:white; } .mytext { color:black; }
may at first seem like the color would be black, however as you have created a stronger bind (by being more specific earlier) the actual color will be white.
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