<h2>1. Modern Flexbox (Recommended method)</h2>
<div class="flexbox padre">
<div class="hijo">Content here.</div>
</div>
<h2>2. Line-height method</h2>
<div class="line-height padre">
<div class="hijo">Content here. Only works with one line of text.</div>
</div>
<h2>3. CSS Table method</h2>
<div class="table padre">
<div class="hijo">Content here.</div>
</div>
<h2>4. Absolute position and negative margin method</h2>
<div class="absolute padre">
<div class="hijo">Content here.</div>
</div>
<h2>Absolute position and Stretch method</h2>
<div class="stretch padre">
<div class="hijo">Content here.</div>
</div>
<h2>Padding top and bottom method</h2>
<div class="padding padre">
<div class="hijo">Content here.</div>
</div>
<h2>Floating div method</h2>
<div class="floating padre">
<div class="floater"></div>
<div class="hijo">Content here.</div>
</div>
/* General styles, nothing relevant for vertical alignment */
.padre {
background-color: #ccc;
max-width: 400px;
height: 200px;
}
/* Relevant example codes */
/* Example 1: Flexbox method */
.flexbox.padre {
display: flex;
align-items: center;
}
/* Example 2: line-height method */
.line-height .hijo {
line-height: 200px;
}
/* Example 3: CSS table method */
.table.padre {
display: table;
height:200px;
width: 100%;
}
.table .hijo {
display: table-cell;
vertical-align: middle;
}
/* Example 4: Absolute position and negative margin method */
.absolute.padre {
position: relative;
}
.absolute .hijo {
position: absolute;
top: 50%;
}
/* Example 5: Absolute position and stretch method */
.stretch.padre {
position: relative;
}
.stretch .hijo {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
width: 100%;
height: 30%;
margin: auto;
background-color: #b2b2b2; /* Just for you can see it */
}
/* Example 6: Padding method */
.padding.padre {
padding: 5% 0;
height: auto; /* If you set a fixed height, this won't work */
}
.padding .hijo {
padding: 10% 0;
}
/* Example 5: Floating div method */
.floating.padre {
height: 250px;
}
.floating .floater {
float: left;
height: 50%;
width: 100%;
margin-bottom: -50px;
}
.floating .hijo {
clear: both;
height: 100px;
}
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.