- How to apply css to iframe in Html?
- Method 1: Inline Style Attribute
- Method 2: Stylesheet Linked to the Parent Page
- Method 3: Stylesheet Linked to the Iframe Page
- Method 4: CSS in the Parent Page Targeting the Iframe
- Method 5: CSS in the Iframe Page Targeting the Parent Page
- How to Apply CSS to iFrame
- Example
- Adding CSS File to iFrame
- CSS to iFrame: Как Изменить CSS в iFrame
- Добавление CSS файлов в iFrame
- Статьи из данной категории:
- Комментарии ( 3 )
How to apply css to iframe in Html?
Iframes are often used to embed other web pages into a current page, but it can be a challenge to apply CSS styles to the content within an iframe. There are several methods to apply CSS to an iframe, but each has its own limitations and considerations. Here are some ways to apply CSS to iframes:
Method 1: Inline Style Attribute
To apply CSS to an iframe using the inline style attribute, you can follow these steps:
iframe id="my-iframe" src="https://example.com">iframe>
iframe id="my-iframe" src="https://example.com" style="">iframe>
iframe id="my-iframe" src="https://example.com" style="border: 1px solid red; width: 100%; height: 500px;">iframe>
Here’s an example of applying a border and setting the width and height of the iframe using the inline style attribute:
iframe id="my-iframe" src="https://example.com" style="border: 1px solid red; width: 100%; height: 500px;">iframe>
You can also apply CSS to the content inside the iframe by targeting its body element using the contentDocument property.
iframe id="my-iframe" src="https://example.com">iframe>
var iframe = document.getElementById('my-iframe'); var iframeBody = iframe.contentDocument.body; iframeBody.style.backgroundColor = 'blue';
Here’s an example of changing the background color of the content inside the iframe to blue:
iframe id="my-iframe" src="https://example.com">iframe>
var iframe = document.getElementById('my-iframe'); var iframeBody = iframe.contentDocument.body; iframeBody.style.backgroundColor = 'blue';
That’s it! These are some examples of how to apply CSS to an iframe using the inline style attribute.
Method 2: Stylesheet Linked to the Parent Page
To apply CSS to an iframe using a stylesheet linked to the parent page, follow these steps:
- Create a CSS file with the styles you want to apply to the iframe. Let’s call it «iframe-styles.css».
- Link the CSS file to the parent page using the tag in the section of the HTML document. For example:
head> link rel="stylesheet" type="text/css" href="iframe-styles.css"> head>
iframe class="iframe-styling" src="https://www.example.com">iframe>
- In the «iframe-styles.css» file, add a CSS rule that targets the class attribute of the tag. For example:
.iframe-styling border: 2px solid red; width: 100%; height: 500px; >
This will apply a red border, set the width to 100%, and the height to 500 pixels to the iframe with the class attribute of «iframe-styling».
Here is the complete code example:
head> link rel="stylesheet" type="text/css" href="iframe-styles.css"> head> body> iframe class="iframe-styling" src="https://www.example.com">iframe> body>
.iframe-styling border: 2px solid red; width: 100%; height: 500px; >
By following these steps, you can easily apply CSS styles to an iframe using a stylesheet linked to the parent page.
Method 3: Stylesheet Linked to the Iframe Page
To apply CSS to an iframe using a stylesheet linked to the iframe page, follow these steps:
- Create a CSS file with the desired styles. For example, create a file named «iframe-style.css» with the following styles:
body background-color: #eee; >
- In the iframe page, link to the CSS file using the tag. For example, add the following code to the section of the iframe page:
head> link rel="stylesheet" type="text/css" href="iframe-style.css"> head>
- In the parent page, add the allowfullscreen and seamless attributes to the tag. For example, add the following code to the parent page:
iframe src="iframe-page.html" allowfullscreen seamless>iframe>
That’s it! The CSS styles defined in the «iframe-style.css» file will be applied to the content of the iframe.
Here is the complete code for the iframe page:
DOCTYPE html> html> head> link rel="stylesheet" type="text/css" href="iframe-style.css"> head> body> h1>Hello World!h1> p>This is an example of an iframe.p> body> html>
And here is the complete code for the parent page:
DOCTYPE html> html> head> title>Parent Pagetitle> head> body> h1>Welcome to the Parent Pageh1> iframe src="iframe-page.html" allowfullscreen seamless>iframe> body> html>
Method 4: CSS in the Parent Page Targeting the Iframe
To apply CSS to an iframe using CSS in the parent page, you can use the contentDocument property of the iframe to target its contents. Here are the steps to do it:
iframe id="my-iframe" src="http://example.com">iframe>
#my-iframe width: 100%; height: 300px; border: none; >
- To target elements inside the iframe, you can use the contentDocument property to get the iframe’s document object. Here’s an example that changes the background color of a div inside the iframe:
#my-iframe width: 100%; height: 300px; border: none; > #my-iframe .my-div background-color: red; >
var iframe = document.getElementById('my-iframe'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; var myDiv = iframeDoc.getElementById('my-div'); myDiv.style.backgroundColor = 'red';
- If you want to apply styles to the entire iframe document, you can use the contentDocument property to add a tag to the iframe’s head:
#my-iframe width: 100%; height: 300px; border: none; > #my-iframe body background-color: red; >
var iframe = document.getElementById('my-iframe'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; var style = iframeDoc.createElement('style'); style.innerHTML = 'body < background-color: red; >'; iframeDoc.head.appendChild(style);
That’s it! With these steps, you can easily apply CSS styles to an iframe using CSS in the parent page.
Method 5: CSS in the Iframe Page Targeting the Parent Page
To apply CSS to an iframe from the parent page, you can use the contentDocument property to access the iframe’s document object and then manipulate its CSS styles using JavaScript. Here is an example code snippet:
DOCTYPE html> html> head> title>Parent Pagetitle> style> iframe width: 100%; height: 300px; > style> head> body> iframe id="myIframe" src="iframe.html">iframe> script> var iframe = document.getElementById('myIframe'); var iframeDoc = iframe.contentDocument || iframe.contentWindow.document; var style = document.createElement('style'); style.textContent = 'body '; iframeDoc.head.appendChild(style); script> body> html>
In this example, we have an iframe element with an ID of myIframe that loads the iframe.html file. In the parent page, we have defined some CSS styles for the iframe element itself.
To apply additional CSS styles to the iframe’s document, we first get a reference to the iframe element using getElementById . We then use the contentDocument property to get the iframe’s document object. If the iframe is from a different domain, we need to use contentWindow.document instead.
Next, we create a new style element using createElement and set its textContent property to the CSS styles we want to apply to the iframe’s document. In this case, we are setting the background color of the body element to #f0f0f0 .
Finally, we append the new style element to the head element of the iframe’s document using appendChild .
With this approach, you can apply any CSS styles you want to the iframe’s document from the parent page. Just make sure to wait for the iframe to load before trying to access its document object.
How to Apply CSS to iFrame
iFrame is a very convenient way to display an external content on your webpage. However, it’s little bit complicate if you want to add additional or alter the existing CSS style. You cannot simply add CSS on the parent/wrapper page. In this tutorial, we’ll show you how to use JavaScript to inject CSS into iFrame.
In the snippet below, once everything was loaded, we’ll get the iFrame element by ID. Then get the contentDocument and inject our styles into iFrame using innerHTML.
window.onload = function() < let myiFrame = document.getElementById("myiFrame"); let doc = myiFrame.contentDocument; doc.body.innerHTML = doc.body.innerHTML + ''; >
Or you can do it with jQuery.
$("#myiFrame").on("load", function() < let head = $("#myiFrame").contents().find("head"); let css = ''; $(head).append(css); >);
Example
For example, here is the 3D CSS Progressbar tutorial page that we want to add to ours using iframe.
Suppose that we want to change the length of the progress bar to 45%. Unfortunately, we can’t do something like this from our parent CSS.
Let’s try using JavaScript. It’s important that you’ll need to wait until the iFrame was loaded before you can inject the CSS. In this case, we’ll put the code in onload event listener.
window.onload = function() < let frameElement = document.getElementById("myiFrame"); let doc = frameElement.contentDocument; doc.body.innerHTML = doc.body.innerHTML + '.bar '; >
Adding CSS File to 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.
TK Engineer, Web Developer, Ex-Mutual Funds Software Developer. He founded Red Stapler in 2015 to share useful resources for everyone interested in web design, web development and programming. Subscribe his YouTube Channel or Twitter for weekly tips and tutorials.
CSS to iFrame: Как Изменить CSS в iFrame
Добавление CSS стилей на родительской странице не работает для тегов iFrame. Из данного руководства вы узнаете, как с помощью JavaScript изменить CSS стили в iFrame, а также как добавить новые (подключить с помощью link).
Пусть у нас есть iFrame с >
Чтобы добавить новые стили для содержимого iFrame, используем следующий JavaScript код:
window.onload = () => < let iframeName = document.getElementById("iframeName"); let iframeContent = iframeName.contentDocument; iframeContent.body.innerHTML = iframeContent.body.innerHTML + ".iframe-css "; >
Если необходимо добавить в iFrame много CSS стилей, то данный подход не очень удобен. Рассмотрим, как можно подключить новые файлы стилей в теге
Добавление CSS файлов в iFrame
Чтобы добавить новый файл, используем следующий код:
// Добавление css файла в IFRAME window.onload = () => < // создаём новый тег "link" для iFrame и заполняем его "href", "rel" и "type" let iframeLink = document.createElement("link"); iframeLink.href = "fileName.css"; // css файл для iFrame iframeLink.rel = "stylesheet"; iframeLink.type = "text/css"; // вставляем в [0] - индекс iframe frames[0].document.head.appendChild(iframeLink); >
// Вставка CSS в iFrame link $("#iframeName").on("load", () => < let iframeHead = $("#iframeName").contents().find("head"); // находим "head" iFrame let newLink = $("link"); // создаём тег "link" и далее заполняем атрибуты $("link").attr("href", "fileName.css"); $("link").attr("rel", "stylesheet"); $("link").attr("type", "text/css"); $(iframeHead).append(newLink); // вставляем в наш iFrame >);
Таким образом мы создали тег и затем заполнили его атрибуты. Теперь в этом CSS файле вы можете писать все необходимые стили для содержимого iFrame.
Данный способ работает, если iframe находится на вашем домене.
Надеюсь, вам понравилась данная информация. Если вам интересна тема web-разработки, то можете следить за выходом новых статей в Telegram.
Статьи из данной категории:
Комментарии ( 3 )
// вставляем в [0] - индекс iframe frames[0].document.head.appendChild(iframeLink);
Здравствуйте! Большое спасибо за статью. Пока не получается повторить. Подскажите пожалуйста, на вот таком примере, как через CSS можно убрать внизу формы надпись «Создано пользователем с помощью. «