Search code examples
htmlcssnestedflat

HTML/CSS Nesting Confusion


I know this question has probably been asked before and it's also kind-of a generic question so I hope I don't get bashed...

I have a general question about HTML/CSS and nesting. I have been trying to read up on how it works but I haven't found any website that makes it clear to me. So I am hoping someone here can help.

I am trying to understand how CSS nesting works.

Lets say I have the following CSS:

.parent {
    background-color: red;
}
.child {
    background-color: green;
}
.grandchild {
    background-color: blue;
}

and I the following HTML:

<div class="parent">
    <div class="child">
        <div class="grandchild"></div>
    </div>
</div>

When I test this it looks like I would expect.

What confuses me is I have seen some sample websites where they define the HTML as follows:

<div class="parent">
    <div class="parent child">
        <div class="parent child grandchild"></div>
    </div>
</div>

What is the difference between the first HTML and the second? Given the second HTML, would I have to change my CSS to the following:

.parent {
    background-color: red;
}
.parent .child {
    background-color: green;
}
.parent .child .grandchild {
    background-color: blue;
}

?

Or alternatively, what if I use the nested CSS above with the first HTML (without nesting)?

So there are 4 different possibilities when using HTML/CSS nesting*:

  1. Flat HTML / Flat CSS
  2. Flat HTML / Nested CSS
  3. Nested HTML / Flat CSS
  4. Nested HTML / Nested CSS

*forgive my use of the terms nesting and flat if they incorrect, I don't know the formal names.

Would anyone mind explaining to me the consequence of using each possibility and when you should use which?

Thank you.

Clock


Solution

  • In your first HTML/CSS example you have 3 classes used on 3 elements, which you obviously understand.

    In your 2nd HTML you are applying multiple classes to the 2nd two div elements, nothing more complicated than that. CSS rules then apply as to what attributes are applied if multiple classes specify different values for the same attribute.

    In your 2nd CSS you are using the "child of" notation - so:

    .parent .child
    

    means that when you apply .child to an element it will only affect that element if it is a child of .parent

    this page gives great examples: http://css-tricks.com/multiple-class-id-selectors/