Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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; } 
like image 211
scientiffic Avatar asked Oct 01 '13 19:10

scientiffic


1 Answers

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.

like image 122
Josh Crozier Avatar answered Oct 17 '22 10:10

Josh Crozier