Skip to content

Instantly share code, notes, and snippets.

@infinitystylish
Last active December 21, 2015 04:09
Show Gist options
  • Save infinitystylish/6247280 to your computer and use it in GitHub Desktop.
Save infinitystylish/6247280 to your computer and use it in GitHub Desktop.
CSS - Centrar Elemento Horizontal/Vertical
<!DOCTYPE html>
<html>
<head>
<title>Centrado Vertical-Horizontal</title>
<style type="text/css">
.space{
width: 100%;
height: 20px;
}
/******Primer Metodo**********/
#square-parent{
width: 50%;
height: 400px; /* Es necesaria una altura definida*/
background-color: #CCC;
position: relative;
margin: 0 auto;
}
#square{
width: 100px; /*Funciona con porcentaje*/
height: 100px; /*Funciona con porcentaje*/
position: absolute;
left: 0;
top: 0;
right: 0;
bottom: 0;
margin: auto;
background-color: #000;
overflow: auto;
}
/******Segundo Metodo**********/
#square-parent2{
width: 50%;
height: 400px; /* Es necesaria una altura definida*/
background-color: #CCC;
position: relative;
margin: 0 auto;
}
#square2{
width: 100px;
height: 100px;
position: absolute;
left: 50%;
top: 50%;
margin: -50px 0 0 -50px; /* top: 50px; right:0; bottom: 0; left: -50px;*/
background-color: #000;
overflow: auto;
}
/******Tercer Metodo**********/
#square-parent3{
width: 50%;
height: 300px; /* NO es necesaria una altura definida*/
display: table;
margin: 0 auto;
text-align: center;
}
#text{
background-color: #CCC;
display: table-cell;
vertical-align: middle;
}
/******Cuarto Metodo**********/
/* This parent can be any width and height */
#square-parent4 {
text-align: center;
height: 500px;
width: 500px;
background-color: #CCC;
margin: 20px auto;
}
#square-parent4:before {
content: '';
display: inline-block;
height: 100%;
vertical-align: middle;
margin-right: -0.25em; /* Adjusts for spacing */
}
/* The element to be centered, can
also be of any width and height */
#square4 {
display: inline-block;
vertical-align: middle;
}
#square4-1 {
width: 300px;
background: black;
height: 100px; /* Puede o no llevar una altura definida*/
margin: 0 auto;
color: white;
margin: 0 0 20px;
}
#square4-2 {
width: 300px;
background: black;
height: 200px; /* Puede o no llevar una altura definida*/
margin: 0 auto;
color: white;
}
</style>
</head>
<body>
<!-- Primer Metodo -->
<div id="square-parent">
<div id="square"></div>
</div>
<div class="space"></div>
<!-- Segundo Metodo -->
<div id="square-parent2">
<div id="square2"></div>
</div>
<div class="space"></div>
<!-- Tercer Metodo -->
<div id="square-parent3">
<div id="text">
<p>Hi Im centered<p>
<p>All content you want<p>
</div>
</div>
<!-- Cuarto Metodo -->
<div id="square-parent4">
<div id="square4">
<div id="square4-1">
El contenido que sea
</div>
<div id="square4-2">
Otro contenido x
</div>
</div>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment