clp
clp

Reputation: 1528

How do I make the friendly content of an iframe seamlessly part of a page, and inherit styles from the parent page?

How to inherit the font styles from the parent of an iframe. If this is impossible, what could be the alternative?

I maintain a small website. The main menu looks like this:

<!DOCTYPE html>
<html lang="nl">
  <meta charset="utf-8">
  <title>Container for iframe</title>
  <style>
    html, body, #main   { height: 100%; }
    iframe              { height: 100%; width: 100%;}
    body, #main         { font-family: sans-serif; }
    #main               { background-color: azure; }
    iframe, #main       { height: 100%; width: 100%; }
  </style>
  
  <!-- Load web page into iframe content. -->
  <p>Container for iframe</p>
  <p><a href="choice-1.html" target="content">Inherit font from iframe</a>
  <p><a href="choice-2.html" target="content">Choice two</a>
  
  <div id="main" style="background-color: azure; color: red">
   <p>Show iframe below:
   <iframe name="content" src="choice-1.html"></iframe>
  </div>
</html>

This is the html of the child page. In this example, the iframe adopts the background colour of the div it contains. The idea is to import the parent's font:

<!DOCTYPE html>
<html lang="nl">
<meta charset="utf-8">
<title>Test</title>
<style>
  html, body {font-family: inherit;}     */ <------------< */
</style>
  <h1>I am choice one</h1>
  <p>I try to inherit the font from my parent, but failed...
</html>

I am looking for a solution that does not require any knowledge of the pages to be included. I also want the pages to be agnostic about the parent. This makes the overall design more robust and stable.

The problem is that the website should be manageable by someone with limited knowledge of html, css and javascript. A simple solution would be appreciated.

Upvotes: 0

Views: 83

Answers (1)

rdoaa
rdoaa

Reputation: 66

Iframes do not automatically inherit styles from the parent page. But, you can pass the font style as a parameter in the URL of the iframe.

src="choice-1.html?font=sans-serif"

By sending the font information to the child page this way, the child page can retrieve it from the URL. You can achieve this using a JavaScript feature called URLSearchParams.

Here’s the script you’ll need to add to your child page:

<script>
 const urlParams = new URLSearchParams(window.location.search);
 const font = urlParams.get('font');
 if (font) {
     document.body.style.fontFamily = font;
 }
</script>

Upvotes: 3

Related Questions