Centering Elements Regardless of Size
margin: 0 auto; is nice for horizontal centering, but not when the child element is larger than the parent. Also: vertical centering
by pmn4
HTML
<div id="wrapper">
<div id="content1" class="center"></div>
<div id="content2" class="center"></div>
<div id="content3" class="center"></div>
</div>
CSS
#wrapper {
position: relative;
height: 250px;
width: 250px;
background: #ccc;
/* unrelated to demo */
margin: 100px;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#content1 {
height: 150px;
width: 150px;
background: rgba(128, 0, 0, 0.5);
}
#content2 {
height: 50px;
width: 350px;
background: rgba(0, 128, 0, 0.5);
}
#content3 {
height: 350px;
width: 50px;
background: rgba(0, 0, 128, 0.5);
}