Jump to content

Nesting CSS ID/Class selector


dhermanus
 Share

Recommended Posts

Hi I also want to ask about Nesting.. :) Here's some materials baout nesting that I don't understand from HTMLDog. It says :

For example:#top { background-color: #ccc; padding: 1em } #top h1 { color: #ff0; } #top p { color: red; font-weight: bold; } Removes the need for classes or ID's if it is applied to HTML that looks something like this:<div id="top"> <h1>Chocolate curry</h1> <p>This is my recipe for making curry purely with chocolate</p> <p>Mmm mm mmmmm</p> </div> This is because, by separating selectors with spaces, we are saying 'h1 inside ID top is colour #ff0' and 'p inside ID top is red and bold'.This can get quite complicated (because it can go for more than two levels, such as this inside this inside this inside this etc.) and may take a bit of practice.
If I change the CSS code to :
#top { background-color: #ccc; padding: 1em } h1 { color: #ff0; } p { color: red; font-weight: bold; }
This would also give me the same result. :) So why do we need to write it this way?
#top { background-color: #ccc; padding: 1em } #top h1 { color: #ff0; } #top p { color: red; font-weight: bold; }
Thanks,Naruto
Link to comment
Share on other sites

lets say you have this HTML

<div id="top"><p class="text">blah blah blah</p></div><div id="btm"><p class="text">blah blah blah</p></div>

Lets pretend that the text in both the top and btm are the same font, size, etc except we want the top to be red and the bottom to be blue.Using nesting we can write a generic .text class that applies to both and then 2 specific classes that deal with the color...saves use repeating the common stylesCSS

.text{  font-family: sans-serif;  font-size: 13px;  font-weight: bold;}#top .text{  color: red;}#btm .text{  color: blue;}

Does that clear things up?

Link to comment
Share on other sites

To use your exact situation, if you use the following css

#top { background-color: #ccc; padding: 1em } h1 { color: #ff0; } p { color: red; font-weight: bold; }

with this html

<div id="top">  <h1>Header 1</h1>  <p>Paragraph 1</p></div><h1> Header 2</h1><p>Paragraph 2</p>

Both <h1> tags would be yellow, and both <p> tags would appear bold and red. However, if you use the nested css:

#top { background-color: #ccc; padding: 1em } #top h1 { color: #ff0; } #top p { color: red; font-weight: bold; }

This css with the above html, will have the first <h1> and <p> tags appear as styled (yellow, and red bold respectively), while the second will used the default styles.I hope this helps...

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...