Centrar div y contenido con CSS [resuelto]

Os voy a dejar algunos códigos de ejemplos para que veáis cómo centrar horizontalmente y verticalmente un div (y/o su contenido) utilizando CSS. Las explicaciones están (en inglés) en el propio código.

Es fundamental definir correctamente el DTD (primera línea del código). En mi ejemplo uso el transitional.

Ejemplo 1: centrar un div horizontalmente y verticalmente

 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div both horizontally and vertically in the screen</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */
 
	}
	</style>
</head>
 
<body>
	<div class="wrapper">
		This div is centered vertically and horizontally
	</div>
</body>
 
</html>

Y asi se muestra en los dos navegadores por excelencia. Fijaos que está centrado el propio div ¡y no su contenido!:

Firefox (3.6.13)

Internet Explorer (8.0.7600)

Ejemplo 2: div centrado dentro de otro div

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div CONTENTS HORIZONTALLY inside a DIV</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */
 
	}
 
	.centeredContent{
		background-color: #D00;
		color: #0D0;
		width: 400px;
 
		/* the following two lines will center THE DIV ITSELF in the middle of the wrapper div */
		/* but will ONLY WORK IF THE DTD IS CORRECTLY DEFINED!!!! */
		margin-left: auto;
		margin-right: auto; 
 
		/* this line will center the TEXT inside the .centeredContent div  but not the div itself!! */
		/*text-align: center;*/
	}
	</style>
</head>
 
<body>
	<div class="wrapper">
		<div class="centeredContent">
			The content of this DIV is centered in the div
		</div>
	</div>
</body>
</html>

Firefox:

Internet Explorer:

Ejemplo 3: Centrar el CONTENIDO del div en el div que lo contiene
Igual que en el caso anterior, añadiendo simplemente la línea text-align: center;

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div CONTENTS HORIZONTALLY inside a DIV</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */
 
	}
 
	.centeredContent{
		background-color: #D00;
		color: #0D0;
		width: 400px;
 
		/* the following two lines will center THE DIV ITSELF in the middle of the wrapper div */
		/* but will ONLY WORK IF THE DTD IS CORRECTLY DEFINED!!!! */
		margin-left: auto;
		margin-right: auto; 
 
		/* this line will center the TEXT inside the .centeredContent div  but not the div itself!! */
		text-align: center;
	}
	</style>
</head>
 
<body>
	<div class="wrapper">
		<div class="centeredContent">
			The content of this DIV is centered in the div
		</div>
	</div>
</body>
</html>

Firefox:

Internet Explorer:

Ejemplo 4: centrar texto dentro de un div usando line-height (o imágenes con vertical align):
¡Nótese que el atributo vertical-align funciona bien con imágenes si éstas son más grandes que el contenedor!
En este nuevo ejemplo vamos a hacer el div rojo más ancho y vamos a centrar el texto en él usando line-height. Si el texto es más grande que el contenedor, este método tampoco funcionará.

El código es:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div CONTENTS HORIZONTALLY inside a DIV</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */		
	}
 
	.centeredContent{
		background-color: #D00;
		color: #0D0;
		width: 400px;
		height: 200px;  /* lets make the div bigger! */
 
		/* the following two lines will center THE DIV ITSELF in the middle of the wrapper div */
		/* but will ONLY WORK IF THE DTD IS CORRECTLY DEFINED!!!! */
		margin-left: auto;
		margin-right: auto; 
 
		/* this line will center the TEXT inside the .centeredContent div  but not the div itself!! */
		text-align: center;		
 
		/* centrar verticalmente el div dentro del wrapper */
		line-height:12em;	 /* the value has been set with try&error method and will only be valid for ONE line text */
	}
	</style>
</head>
 
<body>
	<div class="wrapper">
		<div class="centeredContent">
			Line 1
		</div>
	</div>
</body>
</html>

Y asi se ve en los navegadores:

Firefox:

Internet Explorer:

Pero, ¿qué sucede si en lugar de una línea de texto queremos escribir más? Si fueran sólo dos líneas bastaría con dividir el line-height anterior entre dos (line-height:6em;). Si fueran tres, dividir entre tres(line-height:4em;). Etcétera. Pero, ¿y si el texto ocupa más líneas? Podríamos hacerlo con , pero también estaríamos dependiendo de cuánto texto introdujésemos…

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div CONTENTS HORIZONTALLY inside a DIV</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */		
	}
 
	.centeredContent{
		background-color: #D00;
		color: #0D0;
		width: 400px;
		height: 200px;
 
		/* the following two lines will center THE DIV ITSELF in the middle of the wrapper div */
		/* but will ONLY WORK IF THE DTD IS CORRECTLY DEFINED!!!! */
		margin-left: auto;
		margin-right: auto; 
 
		/* this line will center the TEXT inside the .centeredContent div  but not the div itself!! */
		text-align: center;		
 
		/* centrar verticalmente el div dentro del wrapper */
		line-height:1em;	
 
		/* lets now use padding-top to center the text vertically in the red div */
		padding-top: 15px; /* this value is set with try&error method and it is content-dependent. Ug. */
 
	}
	</style>
</head>
 
<body>
	<div class="wrapper">
		<div class="centeredContent">
			Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ultricies risus euismod risus consectetur ut lacinia dolor vestibulum. Aenean condimentum enim ut odio porttitor vestibulum bibendum lectus ultrices. Etiam scelerisque sodales arcu vel ullamcorper. Mauris cursus massa ac neque aliquam faucibus. Proin pretium mollis neque, in ornare libero auctor at. Fusce vitae enim massa. Pellentesque sed tellus sit amet risus sollicitudin interdum. Etiam dolor tortor, molestie in tempor vel, gravida quis justo. Aliquam erat volutpat. Morbi sodales dignissim posuere. Praesent adipiscing arcu non mi pulvinar mattis. Donec ipsum quam, tristique ac fermentum vitae, eleifend eu risus. 
		</div>
	</div>
</body>
</html>

La solución pasa por utilizar display:table-cell; y vertical-align:middle.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html lang="es" xmlns="http://www.w3.org/1999/xhtml">
 
<head>
	<title>Center div CONTENTS HORIZONTALLY inside a DIV</title>
	<style>
	.wrapper {
		background-color: #AAA;
		color: #000;
 
		height: 500px;             /* height = H1 */
		width: 600px;							 /* width  = W1 */
 
		position: absolute;        /* we want it to be absolutely centered */
		left: 50%;                 /* with these two lines i set the begining of the div in the center of screen */
		top: 50%;
															/* but I have to "correct" it because I do not want the *BEGINING* to be centered. But the div itself. */
		margin-left: -300px;      /* correct1-> set to left W1/2 so that the middle point of the div is centered horizontally */
		margin-top: -250px;       /* correct2-> set to top H1/2 so that the midddle point of the div is centered vertically */		
	}
 
	.centeredContent{
		background-color: #D00;
		color: #0D0;
		width: 400px;
		height: 200px;
 
		/* the following two lines will center THE DIV ITSELF in the middle of the wrapper div */
		/* but will ONLY WORK IF THE DTD IS CORRECTLY DEFINED!!!! */
		margin-left: auto;
		margin-right: auto; 
 
		/* this line will center the TEXT inside the .centeredContent div  but not the div itself!! */
		text-align: center;		
 
    /* to center the text within the red div we use the following two lines */
		display:table-cell;
		vertical-align: middle;
	}
 
	</style>
</head>
 
<body>
	<div class="wrapper">
		<div class="centeredContent">
					Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ultricies risus euismod risus consectetur ut lacinia dolor vestibulum.
		</div>
	</div>
</body>
</html>

Pero si nos fijamos el div rojo (contenedor del texto) se nos desplazará a la izquierda (muestro solo el pantallazo de Internet Explorer 8, porque en Firefox se ve igual):

Ire completando el post con más ejemplos. Si os quedan dudas, podéis empezar a leer éste tutorial

One Thought on “Centrar div y contenido con CSS [resuelto]

  1. Rubén on 15/06/2012 at 19:43 said:

    Qué pasa campeón!

    Tengo un problema con esto, y es que si hago la ventana muy pequeña el contenido se centra perdiendo los bordes derecho e izquierdo, en cambio si lo hago desde esta o cualquier web profesional, el contenido se desplaza hasta alcanzar el borde izquierdo, en este momento se para y solo se pierde por la banda derecha. No sé si me explico xD

    Un abrazo!!!

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

Post Navigation