tags:

views:

660

answers:

4

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?

+1  A: 

It must have a width assigned ( i.e. width:500px;) and then margin:auto; should do it.

PaulBM
Not in Internet Explorer :(
Thinker
+3  A: 
<style type="text/css"> 
.Div1 {  
position:absolute;  
top:50%;  
left:50%;  
margin:-100px 0 0 -100px;  
width:200px;  
height:200px;  
border:1px solid #9999FF;  
}  
</style> 


<div class="Div1">
</div>
Mike108
Set z-index to place the div above all other objects
Mike108
It is horizontal center and vertical center.
Mike108
Do I set the margins according to width and height?
dani
Because it doesn't have a fixed width...
dani
Yes. If you don't have fixed width or height you have to use JS to get those numbers and adjust your position accordingly. At that point, though, you can just adjust `left` and `top` to reflect the proper offset and forget about margins entirely.
Eric Meyer
@Eric Meyer , can you show the JS code for that?
dani
A: 
div#center {
    margin:auto;
    width:300px;
    height:300px;
    z-index:100;
}

That CSS code should do it. The margin:auto centers it, and the z-index:100 puts it to the top.

Macha
It is horizontal center only, and is not horizontal center and vertical center.
Mike108
+3  A: 

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.

ndp
But IE6 can not recognize position:fixed.
Mike108