简体   繁体   中英

How to make a DIV inherit it's “em” value from its parent's parent

We all know that the elastic layout "em" value for a given object is relative to the object's parent, eg:

<div id="div1" style="font-size:1em;">
<p>Hello</p>
<div id="div2" style="font-size:0.5em;">
<p>Hello</p>
<div id="div3" style="font-size:0.5em;">
<p>Hello</p>
</div>
</div>
</div>

But is it possible to make a subordinate DIV "reset" it's em value, or get its value from a parent higher up the chain?

Basically, I have some nested DIVs, and I want one of the inner ones to use the document's own em value. Using 1em is no good, as one of the DIV's parents already uses a fractional value.

Thanks in advance

Simon

Update : Since this answer was originally written, a new unit has been added to CSS.

rem is the root em and is:

Equal to the computed value of font-size on the root element.

This is "the document's own em value".


No, it isn't. font-sizes set with the em unit are explicitly relative to the parent element's font-size.

The closest you can come is to know all the changes and account for that when calculating.

eg since the #div2 has a font-size of 0.5em, to make #div3 have the same font-size as #div1 you would need to set font-size: 2em

Other lengths (with as width values) are relative to the current element's font-size, and you would have to make similar calculations for those.

You may want to reconsider the use of CSS classes instead of styles, as this will solve your problem. Is there a reason you are using style instead of a CSS Class?

<div id="div1">
<p class="font1em">Hello</p>
<div id="div2">
<p class="fonthalfem">Hello</p>
<div id="div3">
<p class="fonthalfem">Hello</p>
</div>
</div>
</div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM