Código de CSS - Centrar un div

Imágen de perfil

Centrar un divgráfica de visualizaciones


CSS

Actualizado el 10 de Noviembre del 2015 por Administrador (718 códigos) (Publicado el 27 de Octubre del 2007)
270.417 visualizaciones desde el 27 de Octubre del 2007
Código que muestra como centrar un div en el centro de la pantalla, tanto verticalmente como horizontalmente.
Probado en IE 5,6,7, Firefox 2 y Opera 9.

Versión 1
estrellaestrellaestrellaestrellaestrella(14)

Actualizado el 10 de Noviembre del 2015 (Publicado el 27 de Octubre del 2007)gráfica de visualizaciones de la versión: Versión 1
270.418 visualizaciones desde el 27 de Octubre del 2007
estrellaestrellaestrellaestrellaestrella
estrellaestrellaestrellaestrella
estrellaestrellaestrella
estrellaestrella
estrella

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html>
<head>
	<title>div centrado verticalmente y horizontalmente</title>
	<style>
	.centrar
	{
		position: absolute;
		/*nos posicionamos en el centro del navegador*/
		top:50%;
		left:50%;
		/*determinamos una anchura*/
		width:400px;
		/*indicamos que el margen izquierdo, es la mitad de la anchura*/
		margin-left:-200px;
		/*determinamos una altura*/
		height:300px;
		/*indicamos que el margen superior, es la mitad de la altura*/
		margin-top:-150px;
		border:1px solid #808080;
		padding:5px;
	}
	</style>
</head>
 
<body>
	<h1>div centrado verticalmente y horizontalmente</h1>
	<div class='centrar'>
		div centrado
	</div>
</body>
</html>



Comentarios sobre la versión: Versión 1 (14)

Cristina
24 de Noviembre del 2007
estrellaestrellaestrellaestrellaestrella
Muchísimas gracias :)
Responder
jonna
29 de Julio del 2008
estrellaestrellaestrellaestrellaestrella
Al leer tu post me ha surgido una pregunta por que en este momento estoy realizando una web y he usado ese metodo para centrar mi página, y funciona perfecto pero:

tengo un menu desplegable que se me descuadra.
Esto antes no me ocurría con la orden text-align = "center" aunque con esta orden no se me centraba bien la página pero el desplegable quedaba en su sitio.

Es un menu desplegable gratuito que modifique en parte, a lo mejor tu sabes que he de retocar en él para que esto no pase. Esta es la hoja de estilos del menu desplegable:

/* this is the clipping region for the menu. it's width and height get set by script, depending on the size of the items table */
.transMenu {
position:absolute;
overflow:hidden;
left:-1000px;
top:-1000px;
text-align: left;
}

/* this is the main container for the menu itself. it's width and height get set by script, depending on the size of the items table */
.transMenu .content {
position:absolute;
}

/* (AQUI CAMPBIAMOS LA POSICION DEL DESPLEGABLE RESPECTO DE LA CAPA atencion al modificar la ubicacion de la capa lateralmente cambia el menu en altura???¿¿¿)this table comprises all menu items. each TR is one item. It is relatively positioned so that the shadow and background transparent divs can be positioned underneath it */
.transMenu .items {
position:relative;
left:-23px; top:-8px;
border:NONE;
z-index:2;
}

.transMenu.top .items {
border-top:none;
}

/* (tipo, color y tamaño letras menu, font weight none para que no este en negrita)each TR.item is one menu item */
.transMenu .item {
color:WHITE;
background-image: none;
font-family: ISOCTEUR;
font-size: 11;
font-weight: NONE;
text-decoration:none;
/* this is a hack for mac/ie5, whom incorrectly cascades the border properties of the parent table to each row */
border:none;
cursor:pointer;
cursor:hand;
}

/* (aqui cambiamos la transparencia del menu desplegable) this DIV is the semi-transparent white background of each menu. the -moz-opacity is a proprietary way to get transparency in mozilla, the filter is for IE/windows 5.0+. */
/* we set the background color in script because ie mac does not use it; that browser only uses a semi-transparent white PNG that the spacer gif inside this DIV is replaced by */
.transMenu .background {
position:absolute;
left:0px;
top:0px;
z-index:1;
-moz-opacity:.0;
filter:alpha(opacity=0);
}

/* (aqui tenemos la transparencia de la linea vertical del borde del menu desplegable, cambiando moz opacity a 0 tenemos el menu sin borde)same concept as .background, but this is the sliver of shadow on the right of the menu. It's left, height, and background are set by script. In IE5/mac, it uses a PNG */
.transMenu .shadowRight {
position:absolute;
z-index:3;
top:3px; width:2px;
-moz-opacity:.0;
filter:alpha(opacity=0);
}

/* (aqui poniendo moz opacity a 0 hacemos totalmente transparente la linea horizontal del borde del menu desplegable) same concept as .background, but this is the sliver of shadow on the bottom of the menu. It's top, width, and background are set by script. In IE5/mac, it uses a PNG */
.transMenu .shadowBottom {
position:absolute;
z-index:1;
left:3px; height:2px;
-moz-opacity:.0;
filter:alpha(opacity=0);
}

/* (color de fondo de las letras al pasar el cursor) this is the class that is used when the mouse is over an item. script sets the row to this class when required. */
.transMenu .item.hover {
background-image: none;
color:#8b8989;
}

/* (para quitar los pngs de los puntos,mas abajo para dar color a las letras)this is either the dingbat that indicates there is a submenu, or a spacer gif in it's place. We give it extra margin to create some space between the text and the dingbat */
.transMenu .item img {
margin-left:-1010px;
}
.textoNoIdent {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
color: WHITE;
text-decoration: none;
}
.formError {
font-family: Arial, Helvetica, sans-serif;
font-size: 12px;
font-weight: bold;
color: WHITE;
border-top: 1px solid #C4CCCC;
border-right: 1px solid #ACB5B5;
border-bottom: 1px solid #6F7777;
border-left: 1px solid #ACB5B5;
padding: 2px 0 2px 0.25em;
background-color: #F5E984;
}
.txtError {
font-family: Arial, Helvetica, sans-serif;
font-size: 11px;
font-weight: bold;
color: #990000;
background-color: #E9E9E9;
padding: 3px;
text-align: justify;
}
Como ves, trae explicaciones de como modificarlo, ya que lo saque de un página gratuita.

Te agrdeceria que me echaras un cable!!!!
Responder
Jonatan
12 de Mayo del 2009
estrellaestrellaestrellaestrellaestrella
justo lo que andaba buscando... gracias por el ejemplo.
Responder
esteban
15 de Agosto del 2009
estrellaestrellaestrellaestrellaestrella
hay dos etiquetas <body> en el ejemplo, pero me sirvió el tuto, gracias!
Responder
prog1000
5 de Abril del 2011
estrellaestrellaestrellaestrellaestrella
Tambien lo puedes conseguir asi:

body{width:780px;margin:0 auto;padding:0px;}
Responder
Gio
1 de Septiembre del 2011
estrellaestrellaestrellaestrellaestrella
gracias, funciona de maravilla!!
Responder
rowilson
22 de Noviembre del 2011
estrellaestrellaestrellaestrellaestrella
falta agregar

body {
min-width:400px; /*ancho del div a centrado*/
min-height:300px; /*altura del div a centrado, así no se sale del espacio*/
}
Responder
Ckarl
10 de Enero del 2012
estrellaestrellaestrellaestrellaestrella
Muy bueno!
Responder
Pablo
21 de Febrero del 2012
estrellaestrellaestrellaestrellaestrella
Muy bueno!!! me re sirbio
Responder
martin
29 de Agosto del 2012
estrellaestrellaestrellaestrellaestrella
thanx karen
Responder
Richard Sumavila
8 de Agosto del 2014
estrellaestrellaestrellaestrellaestrella
Excelente!!!
Responder
Karoline
9 de Septiembre del 2014
estrellaestrellaestrellaestrellaestrella
Gracias, había olvidado como hacerlo y me salio a la perfección.
Responder
Yesid
15 de Septiembre del 2015
estrellaestrellaestrellaestrellaestrella
Super. Muchas Gracias.
Responder
Esteban
29 de Diciembre del 2016
estrellaestrellaestrellaestrellaestrella
Gracias !!!
Responder

Comentar la versión: Versión 1

Nombre
Correo (no se visualiza en la web)
Valoración
Comentarios...
CerrarCerrar
CerrarCerrar
Cerrar

Tienes que ser un usuario registrado para poder insertar imágenes, archivos y/o videos.

Puedes registrarte o validarte desde aquí.

Codigo
Negrita
Subrayado
Tachado
Cursiva
Insertar enlace
Imagen externa
Emoticon
Tabular
Centrar
Titulo
Linea
Disminuir
Aumentar
Vista preliminar
sonreir
dientes
lengua
guiño
enfadado
confundido
llorar
avergonzado
sorprendido
triste
sol
estrella
jarra
camara
taza de cafe
email
beso
bombilla
amor
mal
bien
Es necesario revisar y aceptar las políticas de privacidad

http://lwp-l.com/s1587