10

Using JavaScript, how can I get the actual value for a CSS property which is inherited?

For example, consider the following HTML:

<p><span style="font-size:24pt;">Test #1</span></p>​
<p style="font-size:24pt;">Test <span style="font-weight:bold;">#2</span></p>​

Using the jQuery code $('p span').css('fontSize') will yield 32px not 24pt because it uses getComputedStyle which returns the used value, not the actual inherited value. But sometimes the style will be directly on the element I am targeting, sometimes it will be inherited.

Here is a test case. How can I get the actual inherited CSS of an element using JavaScript?

Josh
  • 10,961
  • 11
  • 65
  • 108
  • The issue here is that the value is being converted to pixels. `32px` is `24pt`. http://reeddesign.co.uk/test/points-pixels.html Check this demo: http://jsfiddle.net/mvqPE/1/ – gen_Eric Apr 02 '12 at 20:06
  • 1
    @Rocket: Right. That's *exactly* the issue I am trying to solve :-p and that's what I mean by `actual` vs `used` value – Josh Apr 02 '12 at 20:15
  • 1
    Pretty sure you can't get the "actual" value (short of reading the `style` attribute). http://stackoverflow.com/a/1314845 – gen_Eric Apr 02 '12 at 20:18
  • It's looking that way... – Josh Apr 02 '12 at 20:22
  • Maybe you can get the px value and convert it to pt... – gen_Eric Apr 02 '12 at 20:24
  • Yeah, someone mentioned I could precompute the `px` values of all the `pt` sizes I have, then use a lookup table to convert. – Josh Apr 02 '12 at 20:25
  • `(32px * 72) / 96 = 24pt` :-P – gen_Eric Apr 02 '12 at 20:27
  • That's an oversimplified formula. `25pt -> 33px` but `33*72/96==24.75pt`. Also this depends on font face, OS, browser, zoom, and a wide variety of other things. – Josh Apr 02 '12 at 20:36
  • Because you are making a web interface (pixels). You should be using pixels and or ems for measurements anyway. Also, never use inline styles, its makes the styles unmanageable for future developers. – laymanje Apr 02 '12 at 20:54
  • 1
    You have no idea what I am doing @laymanje. In fact you're completely wrong. I am developing a *print layout system* and the inline styles are placed there by my CMS. – Josh Apr 02 '12 at 20:57
  • (Unrelated, poor man's private messaging, will delete this soonish: [your PNG clock](http://meta.stackexchange.com/questions/79288/what-time-is-it/79289#79289) seems to be broken?) – Arjan May 15 '12 at 21:18
  • ([That clock](http://josh.gitlin.name/time3.php), by the way, is used in that post from Pekka; see [its source](http://meta.stackoverflow.com/revisions/a7d937c5-b98a-42d1-9b40-944e18a57cc7/view-source).) – Arjan May 15 '12 at 21:39

1 Answers1

2

The answer by @mikerobi would satisfy your test case, but to be more specific the only CSS properties exposed by the browsers are from getComputedStyle, so if it's wrong there that's about as good as it gets. See this answer from another question for more detail.

Community
  • 1
  • 1
Alex Vidal
  • 4,080
  • 20
  • 23