How to apply CSS to iframe?

 

You can apply CSS styles to an <iframe> element by targeting the <iframe> itself or by targeting the content within the <iframe> if it comes from the same domain. Here, I'll provide examples for both scenarios.

Styling the <iframe> Element:

To style the <iframe> element itself, you can use CSS to set properties such as width, height, border, and so on. Here's an example:

html
<!DOCTYPE html> <html> <head> <style> /* Style the iframe element */ iframe { width: 500px; height: 300px; border: 2px solid #007bff; } </style> </head> <body> <iframe src="https://example.com"></iframe> </body> </html>

In this example, we use CSS to set the width, height, and border of the <iframe> element.

Styling the Content within the <iframe> (Same Domain):

If the content within the <iframe> comes from the same domain as your main page, you can use JavaScript to access and modify the content's CSS. Here's an example:

html
<!DOCTYPE html> <html> <head> <style> /* Style the iframe element */ iframe { width: 500px; height: 300px; } </style> <script> // Access the iframe content and apply CSS to elements within it function applyCSS() { var iframe = document.getElementById("myIframe"); if (iframe) { var iframeDocument = iframe.contentDocument || iframe.contentWindow.document; var targetElement = iframeDocument.getElementById("exampleDiv"); if (targetElement) { targetElement.style.backgroundColor = "#ffcc00"; targetElement.style.color = "#333"; } } } </script> </head> <body> <iframe id="myIframe" src="https://example.com"></iframe> <button onclick="applyCSS()">Apply CSS to Content</button> </body> </html>

In this example, we have an <iframe> element with an id of "myIframe" and a button. When you click the button, the JavaScript function applyCSS() accesses the content within the <iframe> and applies CSS styles to a specific element with an id of "exampleDiv." This is done by accessing the contentDocument property of the <iframe> and then manipulating the CSS properties of the target element within it.

Please note that for security reasons, you can only access and modify the content of an <iframe> if it's from the same domain as your main page. Cross-origin restrictions apply if the content comes from a different domain.

Comments