Is there a way to detect if the browser has subpixel precision for elements ?
IE9, unlike any of the other major browsers, has subpixel precision for its elements (an elements width can be 50.25px) and because of that, I need to treat a thing differently.
One way is to use jQuery to detect the browser name and version, but this is deprecated in jQuery and not recommended, instead being suggested that the existence of features should be tested for not the browsers names and versions.
http://jsfiddle.net/KAW3d/1/
You could create an odd-sized container and drop two 50% width elements in it, and find out whether they've been split 50:50 or not.
See http://jsfiddle.net/alnitak/jzrQ6/
It returns
false
on Chrome 22.0.1229.79 on MacOS X 10.8.2, andtrue
on Firefox 15.0.1. I don't have MSIE to test it with.I'm not sure where you got the idea that IE9 is the only browser that supports fractional pixel units, but that assumption is totally incorrect.
From section 4.3 of the spec (emphasis added):
And defining <number>:
Therefore, per spec, the
px
length unit must support fractional numbers.To prove this, take a look at this fiddle in fullscreen and use your browser's zoom function to zoom all the way in:
In this Chrome screenshot, notice that the 5.5px blue box is indeed taller than the 5px red box.
I think the confusion might stem from the fact that the non-standard
element.clientHeight
returns a calculated (rounded) integer value, and that rounding happens differently in different browsers.In my fiddle, for the
clientHeight
of the blue<div>
, IE9 and Firefox 15 at 100% zoom give6
. Chrome 22 and Opera 12 give5
. In all browsers, the value of that property changes as the user changes the browser's zoom level.In other words, it's unreliable.
If you want to do calculations with the actual, fractional units of an element, use
getComputedStyle
.We had to do some serious pixel-perfect calculations recently, and I needed to check whether the browser was going to support subpixel layouts. I created a test for use in Conditionizr or Modernizr using some other answers as guides:
Then you can use with:
You should be able to do the same thing in Modernizr with
Modernizr.addTest()
, but I didn't test it.Obviously I'm using
jQuery
here, but should be pretty simple without it as well.