How to apply css to iframe using jquery?

Member

by lizzie , in category: Javascript , 3 months ago

How to apply css to iframe using jquery?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by kadin , 3 months ago

@lizzie 

To apply CSS to an iframe using jQuery, you can use the .contents() method to access the document inside the iframe and then apply CSS styles to its elements.


Here is an example code snippet to demonstrate how you can apply CSS to an iframe using jQuery:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Apply CSS to iframe using jQuery</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
  // Select the iframe
  var iframe = $('#my-iframe');
  // Access the document inside the iframe
  var iframeDocument = iframe.contents().find('html');
  // Apply CSS styles to the document inside the iframe
  iframeDocument.css('background-color', 'lightblue');
  iframeDocument.find('body').css('font-family', 'Arial, sans-serif');
});
</script>
</head>
<body>

<iframe id="my-iframe" src="https://www.example.com"></iframe>

</body>
</html>


In this example, we are selecting the iframe element with the id my-iframe using jQuery. We then access the document inside the iframe using the .contents() method and apply CSS styles to it. In this case, we are setting the background color of the iframe document to light blue and changing the font family of the body text to Arial.


You can modify the CSS properties and values according to your requirements to style the contents of the iframe.