views:

45

answers:

3

CSS can apply styles in elements through one ID, class or pseudo-selector, but I would like to get the HTML tree, something like in javascript:

<script type = "text/javascript">
    window.onload = function () {
        var div = document.getElementsByTagName ("div");

        div[0].style.backgroundColor = "gray";
        div[0].style.padding = "20px";
    }
</script>

So for example:

<style type = "text/css">
    div[0] { /* Wrong but i tried :( */
        background-color: gray;
        padding: 20px;
    }
</style>

<div >
    <div>...</div>
</div>

I'm tired of assign IDs to millions and millions of elements; is there a way to do this?

A: 

If I understand correctly just use div:first-child.

Jakub Hampl
That would match the first `<div>` that was a child of *any other* element. e.g. with `<div><div>this one</div></div>` it would match the inner `<div>` because it's the first child of the outer `<div>`.
Dean Harding
+1  A: 

Well, technically you could use:

body > div:first-child {
    background-color: gray;
    padding: 20px;
}

Which would match the first div in the <body> of the document, but I don't think that's what you're really after because that wouldn't be all that useful.

I think you're better off just using classes as they're supposed to be used rather than assigning IDs to lots of elements. In general, I find that I usually only assign IDs to the "page layout" elements (i.e. the elements that define the overall structure of the page) and then just use classes for everything else. It never really gets all that unwieldy...

Dean Harding
+1  A: 

If you knew the type of element you had (as in your example) and if CSS3 was an option you could use:

div div:first-of-type {
   ....
}

It won't work in IE though. See Wikipedia article for details. If you don't know the type of the subelement, it won't work either. *:first-of-type is not valid.

TheClair