We help IT Professionals succeed at work.

How to detect screen resolution and size

Robert Granlund
on
Is there a way to detect a website users screen resolution or size?

client wants site to display better in a 1024 wide window, how tough to do a screen res detect and have the site left justify for those who are below 1280X1024?
Comment
Watch Question

Top Expert 2011
Commented:
<script type="text/javascript">
document.write(screen.width+'x'+screen.height);
</script>

Open in new window

Author

Commented:
@nap0leon:

Thank you for the response.  How can I turn that into an if statement using 1280x1024 ?

Thank you in advance.

Commented:
<script type="text/javascript">
if(screen.width=='1280' && screen.height=='1024')
{
// do something
alert('boo');
}
</script>

Open in new window

Top Expert 2011

Commented:
Are you looking to alter the CSS for the page to make it fit inside a smaller width?

Let's presume that your current site has a 100 pixel left margin that you are wanting to remove for lower-res users - the following will set the left-margin to only 10 pixels for such users.
<html>
<head>
</head>
<body style="margin:0 0 0 100px;">
<h1>Hello</h1>
</body>
<script>
if (screen.width < 1280){ document.body.style.margin="0 0 0 10px";}
</script>
</html>

Open in new window

Top Expert 2013

Commented:
I don't think you want to us screen.width and screen.height it does not account for tool bars and sidebars.
Better to use:

<script>
function adjustwidth()
{
   if (window.screen.availWidth <1280)
    {
      document.body.style.width = 1280 + 'px';
      document.body.style.margin=0;
     }
}
onload=adjustwidth;
onresize =adjustwidth;
</script>

Open in new window

Explore More ContentExplore courses, solutions, and other research materials related to this topic.