CSS: center element within a <div> element
Actually this is very straightforward with CSS3 flex boxes.
.flex-container{
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6, BB7 */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Safari 6.1+. iOS 7.1+, BB10 */
display: flex; /* NEW, Spec - Firefox, Chrome, Opera */
justify-content: center;
align-items: center;
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
width: 100px;
height: 100px;
background-color: #f1c40f;
}
<div class="flex-container">
<div class="inner-element"></div>
</div>
UPDATE:
It seems that I didn't read the OP edit at the time I wrote this answer. The above code will center all inner elements (without overlapping between them), but the OP wants just an specific element to be centered, not the other inner elements. So @Warface answer second method is more appropiate, but it still requires vertical centering:
.flex-container{
position: relative;
/* Other styling stuff */
width: 400px;
height: 200px;
background-color: #3498db;
}
.inner-element{
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
/* or 3d alternative if you will add animations (smoother transitions) */
transform: translate3d(-50%,-50%,0);
/* Other styling stuff */
width: 100px;
height: 100px;
background-color: #f1c40f;
}
<div class="flex-container">
<p>Other inner elements like this follows the normal flow.</p>
<div class="inner-element"></div>
</div>
Set text-align:center;
to the parent div, and margin:auto;
to the child div.
#parent {
text-align:center;
background-color:blue;
height:400px;
width:600px;
}
.block {
height:100px;
width:200px;
text-align:left;
}
.center {
margin:auto;
background-color:green;
}
.left {
margin:auto auto auto 0;
background-color:red;
}
.right {
margin:auto 0 auto auto;
background-color:yellow;
}
<div id="parent">
<div id="child1" class="block center">
a block to align center and with text aligned left
</div>
<div id="child2" class="block left">
a block to align left and with text aligned left
</div>
<div id="child3" class="block right">
a block to align right and with text aligned left
</div>
</div>
This a good resource to center mostly anything.
http://howtocenterincss.com/