John T
John T

Reputation: 1078

Is it possible to have multiple ID selectors in CSS

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.

Upvotes: 0

Views: 3361

Answers (5)

Sander Koedood
Sander Koedood

Reputation: 6347

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.

Upvotes: 2

Sunil Hari
Sunil Hari

Reputation: 1776

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

Upvotes: 5

athar13
athar13

Reputation: 382

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.

Upvotes: 1

Vernard Luz
Vernard Luz

Reputation: 291

Yes this is possible.

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

#test, #anotherTest {
    color:red;
}

Upvotes: 2

Michel Tom&#233;
Michel Tom&#233;

Reputation: 389

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;
}

Upvotes: 0

Related Questions