[html] Center icon in a div - horizontally and vertically

I'm having issues centering icons (both vertically and horizontally) in a parent div. I have many parent divs on my page that are different sizes, so I want to be able to proportionally place icons in the center of each parent div. Here's a JSFiddle of the problem:

JsFiddle

HTML

<div class="img_container">
  <i class="icon-play-circle"></i>
</div>
<br>
<div class="img_container2">
  <i class="icon-play-circle"></i>
</div>

CSS

.img_container{
    width:100px;
    height:100px;
    position:relative;
    background:red;
}

.img_container2{
    width:100px;
    height:50px;
    position:relative;
    background:blue;
}

.icon-play-circle{
    position:absolute;
    top:45%;
    left:45%;
    color: white;
}

This question is related to html css

The answer is


Here is a way to center content both vertically and horizontally in any situation, which is useful when you do not know the width or height or both:

CSS

#container {
    display: table;
    width: 300px; /* not required, just for example */
    height: 400px; /* not required, just for example */
}

#update {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}

HTML

<div id="container">
    <a id="update" href="#">
        <i class="icon-refresh"></i>
    </a>
</div>

JSFiddle

Note that the width and height values are just for demonstration here, you can change them to anything you want (or remove them entirely) and it will still work because the vertical centering here is a product of the way the table-cell display property works.


Horizontal centering is as easy as:

text-align: center

Vertical centering when the container is a known height:

height: 100px;
line-height: 100px;
vertical-align: middle

Vertical centering when the container isn't a known height AND you can set the image in the background:

background: url(someimage) no-repeat center center;