You have two options:
Javascript:
var container = document.querySelector('.fixo'),
w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
container.style.top = (y / 2) - (container.clientHeight / 2) + 'px';
container.style.left = (x / 2) - (container.clientWidth / 2) + 'px';
CSS:
.fixo {
width:100px;
height:50px;
background:#000;
position:fixed;
top:50%; left: 50%;
}
The javascript version calculates the height and width of the screen, divides by half and subtracts half the width or respective height of the element.
The CSS version is approximate. You can adjust if the measurements are +/- static. For modern browsers the solution from @bfavaretto is ideal.
Edit:
In cases where it is necessary to support anti-user browsers I suggest using Feature-Detection. That is, detect if the browser supports the calc()
in the CSS (as @bfavaretto suggested), and if no do positioning via Javascript.
Example:
CSS
.fixo {
width:100px;
height:50px;
background:#000;
position:fixed;
top:0;
left: calc(50% - 50px);
}
Javascript
// usando o feature detect do Modrnizer
var calc = (function(){
var dummy = document.createElement('div');
var props = ['calc', '-webkit-calc', '-moz-calc', '-o-calc'];
for (var i=0; i<props.length; ++i) {
var prop = props[i];
dummy.style.cssText = 'width:' + prop + '(1px);';
if (dummy.style.length)
return prop;
}
})();
if (!calc) {
var container = document.querySelector('.fixo'),
w = window,
d = document,
e = d.documentElement,
g = d.getElementsByTagName('body')[0],
x = w.innerWidth || e.clientWidth || g.clientWidth,
y = w.innerHeight|| e.clientHeight|| g.clientHeight;
container.style.top = (y / 2) - (container.clientHeight / 2) + 'px';
container.style.left = (x / 2) - (container.clientWidth / 2) + 'px';
}
If you put
margin-left e right com auto
also http://jsfiddle.net/filadown/9d52oyty/3/– Gabriel Rodrigues