0

Is this correct and does it work correctly across browsers?

<div id="test">
  Some stuff
    <div id="anotherTest">
      More stuff
    </div>
  Even more stuff
</div>

CSS...

#test #anotherTest {
  color:red;
}

Only "More stuff" would be in red.

I know I could use classes and there are several different ways to achieve this but basically I'm asking about selecting an element with CSS via several IDs?

Thanks.

John T
  • 1,078
  • 3
  • 14
  • 29
  • 1
    in your example if you set #test to red, #anotherTest will be red too by inherit of parent, if there is no other css that change it. – aahhaa Aug 07 '14 at 13:12
  • 4
    Sure, you can do that, but it is meaningless, since there can only be one `#anotherTest` element in your document. –  Aug 07 '14 at 13:12
  • 2
    Sure that will work, just make sure that the `id` is only used *once per page* – misterManSam Aug 07 '14 at 13:13

5 Answers5

5

Yes this approach is possible

#test #anotherTest {
  color:red;
}

It selects the element with id anotherTest which has the ancestor with id test

Please READ this

Sunil Hari
  • 1,716
  • 1
  • 12
  • 20
2

To answer your question, it works cross browser, and what you wrote is correct. Only "More stuff" will be in red.

But it is not recommended to use ID's for styling. A nice reference to read more about this can be found here. The entire article is a great read by the way, if you want to learn more about writing good CSS!

The most important part of it, concerning IDs is:

  • IDs can never be used more than once in a page.
  • Classes can exist only once, or a million times in a page.
  • IDs can often have their traits abstracted out into many reusable classes.
  • An ID is infinitely more specific than a class.
  • This means no amount of chained classes can override an ID.
Sander Koedood
  • 6,007
  • 6
  • 25
  • 34
1

Yes this is possible.

If you want both #anotherTest and #test to be red, add a comma.

#test, #anotherTest {
    color:red;
}
Vernard Luz
  • 281
  • 3
  • 7
1

There are several ways to style a web page using CSS, but it seems your question is not only related to style but rather even on selectors. Check out the below w3school link about CSS Selectors

http://www.w3schools.com/cssref/css_selectors.asp

and an excellent demo of CSS Selectors in action

http://www.w3schools.com/cssref/trysel.asp?selector=.intro

And it supports across all popular browsers.

athar13
  • 382
  • 1
  • 8
0

You should try to use classes always, i.e:

<div class="test">
  Some stuff
    <div class="anotherTest">
      More stuff
    </div>
    <div class="andAnotherTest">
      Even More stuff
    </div>
  Even more stuff
</div>

and then in css:

.test .anotherTest {
   color: red;
}

.test .andAnotherTest {
  color: green;
}
misterManSam
  • 24,303
  • 11
  • 69
  • 89
Michel Tomé
  • 389
  • 2
  • 11