4

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

<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

Simon Catlin
  • 2,141
  • 1
  • 13
  • 15

2 Answers2

6

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.

e.g. 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.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks David. I thought as much. I was hoping to avoid having to perform reciprocal calculations. Vote++ and answer. – Simon Catlin Nov 29 '10 at 20:14
0

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> 
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
  • 1
    I don't think there's any difference wether `font-size` is set using element styles or css classes. Font size expressed in `em`s is relative either way. – Athari Nov 28 '10 at 21:31
  • Thanks Eric. The above example was just to demonstrate the problem; I do generally use classes. As Athari said, the problem remains! – Simon Catlin Nov 28 '10 at 21:41
  • I'm saying changing the thought process from trying to make something inherit from a parent.parent.parent.. etc etc which doesn't work, to just using a CSS class that has the size you want on the DIV you want. – Erik Philips Nov 28 '10 at 21:41
  • — em units still give font sizes relative to the parent element. If you're suggesting "Use a non-relative unit" then it makes no difference if you do that inline or further up the cascade. – Quentin Nov 29 '10 at 14:41
  • I've modified my answer to what I believe should have been done instead. – Erik Philips Dec 01 '10 at 05:10