¿Cuál es la mejor manera de centrar un elemento `
Sé que margin-left: auto; margin-right: auto;
centrará en horizontal, pero ¿cuál es la mejor manera de hacerlo también en vertical?
El truco principal en esta demo es que en el flujo normal de los elementos que van de arriba a abajo, por lo que el margin-top: auto
se establece en cero. Sin embargo, un elemento absolutamente posicionado actúa igual para la distribución del espacio libre, y de manera similar puede ser centrado verticalmente en el top
y bottom
especificados (no funciona en IE7).
div
.begin snippet: js hide: false console: true babel: false -->
div {
width: 100px;
height: 100px;
background-color: red;
position: absolute;
top:0;
bottom: 0;
left: 0;
right: 0;
margin: auto;
}
<div></div>
Fin del fragmento;
Aquí hay un script que escribí hace un tiempo (está escrito usando la biblioteca jQuery):
var centerIt = function (el /* (jQuery element) Element to center */) {
if (!el) {
return;
}
var moveIt = function () {
var winWidth = $(window).width();
var winHeight = $(window).height();
el.css("position","absolute").css("left", ((winWidth / 2) - (el.width() / 2)) + "px").css("top", ((winHeight / 2) - (el.height() / 2)) + "px");
};
$(window).resize(moveIt);
moveIt();
};