31

In order to better balance out a page I am working on I would like to find a way to increase the top margin of a DIV depending on the screen resolution. What is my best way to set these dimensions with jQuery or Javascript?

Brian Webster
  • 30,033
  • 48
  • 152
  • 225
Brad Birdsall
  • 1,753
  • 3
  • 23
  • 27

5 Answers5

74

To get screen resolution in JS use screen object

screen.height;
screen.width;

Based on that values you can calculate your margin to whatever suits you.

RaYell
  • 69,610
  • 20
  • 126
  • 152
  • I'm just learning Javascript; any chance you show me the approach you would take to calculate the height and add a certain margin-top to it? The ID of the div I'm adjusting is "port-cont". – Brad Birdsall Aug 13 '09 at 15:32
  • Well you have a screen height given, you must subtract something for browser menu, status bar etc. It's hard to say how much would that be because it depends of the browser. Then you should experiment with different sizes for your elements until you get the site to look just right. If I may suggest I don't know if JS is what you are looking for. You could just set height in CSS stylsheet to some percent value that will always be set right without reading screen resolution in JS. – RaYell Aug 13 '09 at 16:12
  • Helpful tutorial -- http://www.w3schools.com/jsref/prop_win_innerheight.asp – Uncle Iroh Aug 01 '16 at 12:55
22

Here is an example on how to center an object vertically with jQuery:

var div= $('#div_SomeDivYouWantToAdjust');
div.css("top", ($(window).height() - div.height())/2  + 'px');

But you could easily change that to whatever your needs are.

Bryan Denny
  • 27,363
  • 32
  • 109
  • 125
5

Another example for vertically and horizontally centered div or any object(s):

 var obj = $("#divID");
 var halfsc = $(window).height()/2;
 var halfh = $(obj).height() / 2; 

 var halfscrn = screen.width/2;
 var halfobj =$(obj).width() / 2; 

 var goRight =  halfscrn - halfobj ;
 var goBottom = halfsc - halfh;

 $(obj).css({marginLeft: goRight }).css({marginTop: goBottom });
umutkeskin
  • 128
  • 2
  • 3
4

Check out the jQuery dimensions plugin

Colin
  • 10,630
  • 28
  • 36
2
var space = $(window).height();
var diff = space - HEIGHT;
var margin = (diff > 0) ? (space - HEIGHT)/2 : 0;
$('#container').css({'margin-top': margin});
nhahtdh
  • 55,989
  • 15
  • 126
  • 162
NaijaBoy
  • 148
  • 2
  • 7