View Full Version : Get CSS pixels in JS

11-24-2012, 09:46 AM
I am trying to use JavaScript to get the number of CSS pixels that a device has.

Basically, an old iPad has 1024x768 and a new one has 2048x1536 actual pixels, but they both have the same 1024x768 CSS pixels (the new one is a Retina / High DPI device).

If I use screen.width and screen.height then in non-Apple stuff it shows the actual screen pixels, not the CSS pixels.

screen.width/screen.heigh does actually return the CSS pixels on Apple stuff (so it returns 1024x768 on the new iPad).

The Samsung Galaxy SIII however returns the device pixels, which is no good.

I need a uniform way to return the CSS pixels.

device name / device width pixels / CSS width pixels / screen.width returns
old iPad / 1024 / 1024 / 1024
new iPad / 2048 / 1024 / 1024
an old mobile / 480 / 480 / 480
Samsung Galaxy SIII / 720 / 360 / 720

screen.innerWidth and .outerWidth won't work as on desktops the browser might not be fully opened.

I need both the height and width of the screen's CSS pixels.

11-24-2012, 08:59 PM
Why do you care how big the screen is when you can't use the space outside the browser viewport to display anything?

To get the browser viewport size you could use the following:

viewport = {
'width': window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth,
'height': window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight

and then reference the width and height using viewport.width and viewport.height

The only time you can use anything outside of the viewport is where you are opening a new window and then screen.width and screen.height are the values you would need to work with.

If neither of those provide what you need then you will need to explain in detail just exactly what you want it for as there is no way to get what you are asking for and so an entirely different approach would be required.

rnd me
11-25-2012, 08:39 PM
you can use css media queries to apply a specific value to something based on css screen size, and then sniff that value using javascript.

<div id='hint'></div>

@media (min-width:600px) { #hint { background-color: rgba(0,0,0, 0.01); } }
@media (min-width:990px) { #hint { background-color: rgba(0,0,0, 0.05); } }
@media (min-width:1200px){ #hint { background-color: rgba(0,0,0, 0.09); } }

Math.floor(parseFloat(getComputedStyle(hint, null)['backgroundColor'].split(",").slice(-1)[0]) * 100)

); //shows a 1, 5, or 9 depending on your screen