Center icon in a div - horizontally and vertically [duplicate]
Solution 1:
Since they are already inline-block
child elements, you can set text-align:center
on the parent without having to set a width
or margin:0px auto
on the child. Meaning it will work for dynamically generated content with varying widths
.
.img_container, .img_container2 {
text-align: center;
}
This will center the child within both div
containers.
UPDATE:
For vertical centering, you can use the calc()
function assuming the height of the icon is known.
.img_container > i, .img_container2 > i {
position:relative;
top: calc(50% - 10px); /* 50% - 3/4 of icon height */
}
jsFiddle demo - it works.
For what it's worth - you can also use vertical-align:middle
assuming display:table-cell
is set on the parent.
Solution 2:
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.