How do I select elements within a #document in CSS?

css, css-selectors, html

Solution

The given listing appears to be a DOM inspector view. In this case, `#document` doesn't refer to an arbitrary element with an id of "document" — it refers to the document hosted within an `<iframe>` (see `Node.nodeName`). You can see this in Firefox's and Chrome's DOM inspectors; in fact, you can even try it right now by pointing either browser to `data:text/html,<iframe>`, opening the inspector and expanding the `<iframe>` node. IE shows the nested tree as well, but without the `#document` marker.

If you're seeing the background image bleed from the host document into the iframe, that means the document in the iframe doesn't have its own background.

Selectors cannot penetrate multiple/nested document trees; they are localized to the context document. This means that you cannot target elements in a document hosted within an `<iframe>` from within the document that contains that `<iframe>`. If you need to apply styles to elements in a document within an `<iframe>`, the CSS needs to be directly applied within that inner document, and the selectors written as though you were working with just that document.

In the somewhat less likely event that the given listing is actual source markup rather than a DOM inspector view, and `#document` is in fact an arbitrary element with an id of "document", then your inner `<html>` and `<body>` elements have been written off, as an HTML DOM may only contain exactly one `<html>` and one `<body>` element at a time; these would be your outer ones, not the inner ones. In that case, you could try selecting `#document` and applying the background to that instead, but no guarantees that it'll work correctly.

Problem

I'm trying to set the background-image of the outer `<body>` tag in CSS: ``` <html> <body> ... #document <html> <body> </body> </html> ... </body> </html> ``` However, I can't even seem to select one of the `<body>` tags without affecting the other. They have no IDs, and when I try selecting via child selectors that `#document` complicates things (I don't even know what it is). If I try something like `body html body {...}`, the `#document` acts like a barrier that I can't get past, so it doesn't select the inner body tag. Any ideas for how to select one of the body tags?

Original source