Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Css–selector for when a html-document is inside an iframe?

Tags:

css

I'm trying to make a css-selector that assigns diffrent properites based on weather the html is inside an iframe or not. I tried this:

html:not(:root) body {
    background: black !important;
}

I expect this to apply background: black; to the body if it's inside an iframe, but it doesn't, why? And are there any css options? I could always check with javascript if html is root.

IE8 support not requierd.

like image 276
Himmators Avatar asked Feb 18 '14 01:02

Himmators


People also ask

Can you target CSS in an iframe?

You can add entire CSS file instead of injecting separated styles by creating link and add it to the iframe's head. This method does not work with cross domain content. You'll need to set appropriate CORS header but it's not recommended due to security risks.

How do you know if an element is inside an iframe?

In short, to check if a page is in an iframe, you need to compare the object's location with the window object's parent location. If they are equal, then the page is not in an iframe; otherwise, a page is in an iframe.

Can I style elements inside an iframe?

You can not change the styles of the page that resides within the iframe.

Can you style HTML in iframe?

You will not be able to style the contents of the iframe this way. My suggestion would be to use serverside scripting (PHP, ASP, or a Perl script) or find an online service that will convert a feed to JavaScript code. The only other way to do it would be if you can do a serverside include.


2 Answers

CSS is only scoped within the same document. An iframe is an entire document in its own right, and so a CSS rule that applies to the page that contains that iframe cannot apply to the page that's within that iframe.

This means that as far as HTML and CSS are concerned, html is always :root (and therefore can never be :not(:root)).

Unless you are able to transfer this CSS from the containing page to the page within the iframe (using a script for example), I don't believe there is a way using just CSS.

like image 166
BoltClock Avatar answered Oct 17 '22 03:10

BoltClock


It is probably possible to do the styling in an iframe with JavaScript.

document.querySelector('iframe').contentDocument.body.querySelector('#some-element').style.background-color = 'red';

IMPORTANT: Make sure that the iframe is on the same domain, otherwise you can't get access to its internals. That would be cross-site scripting.

Accessing elements inside iframes with JavaScript document futher here: Javascript - Get element from within an iFrame

like image 25
ThorSummoner Avatar answered Oct 17 '22 04:10

ThorSummoner