Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to position div in the center of the screen?

Tags:

javascript

css

Actually in the center of current view, above all other objects. Cross-browser and without 3rd party plugins and etc.

Via CSS or Javascript

UPDATE:

I tried to use Javascript's Sys.UI.DomElement.setLocation() but this positioning object not in absolute location but relative to it's parent.
Is there a function to put in absolute location?

like image 523
dani Avatar asked Aug 29 '09 16:08

dani


People also ask

How do you put a box in the middle of the page in HTML?

How To Center Your Website. Use a container element and set a specific max-width . A common width many websites use is 960px. To actually center the page, add margin: auto .

How do I move a box to center in CSS?

Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.


1 Answers

To have it center in the browser, regardless of the page scroll (which is probably what you want), position: fixed will be more reliable. Amending mike108's code:

<style type="text/css"> 
.centered {  
  position:fixed;
  z-index: 100;  
  top:50%;  
  left:50%;  
  margin:-100px 0 0 -100px;  
  width:200px;  
  height:200px;  
}  
</style>

This assumes you have a fixed size box you are showing. If you don't have a fixed size box, you'll need to use Javascript to measure the window and the div and position it explicitly (again, fixed is probably the way to go).

Do test on all your browsers, though. There may be something we're not thinking of.

I'd actually recommend you look at one of the Javascript plugins that does this, at least for a starting point. They have figured it out, even if you don't want to use their code. I think I used jqModal as a starting point.

like image 57
ndp Avatar answered Sep 16 '22 23:09

ndp