Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Confused about CSS inheritance

Tags:

css

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.

like image 291
billy vandory Avatar asked Jul 26 '10 23:07

billy vandory


People also ask

How is the concept of inheritance applied in CSS?

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.

What does inherited value mean?

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.


2 Answers

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.

like image 166
Mike Avatar answered Sep 20 '22 19:09

Mike


#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.

like image 42
balupton Avatar answered Sep 22 '22 19:09

balupton