How do I vertically center an image whose size can change in a div?

How do I vertically center an image with css when I don't know what height of the image will be? The image, and thus the height, will be provided by the server at run-time, and it could be any number of heights. Knowing this, I created a div within a div, more or less following method 1 of the tutorial found here: http://phrogz.net/css/vertical-align/. But that only works when you know the height of the content you are trying to center, I believe. So how on earth do I vertically center this:

<div class="galleryItem">
    <a href="wherever">
    <img src="whatever" width="173" height="155">
       <div class="galleryTitle">
           <div class="galleryImg">
               <img src="centerMeVertically.jpg">
           </div>
       </div>
    </a>
</div>

Here is the CSS which is failing:

   .galleryItem {
    float: left;
    border-style: solid;
    border-width: 1px;
    border-color: #b78e18;
    margin: 7px 4px;
    padding: 5px;
    width: 173px;
    height: 190px;
    position: relative;
}

.galleryTitle {
    height: 33px;
    width: 173px;
    position: relative;
}

.galleryImg {
     width: 173px;
     height: 30px;
     position: absolute;
     top: 50%;
     margin-top: -15px;
 }

.galleryImg > img {
     display: block;
     margin-left: auto;
     margin-right: auto;
 }

Answers


A table-cell has the ability to align its content to vertically center. So we need to change the behavior of div to table-cell by changing its 'display' property to 'table cell'.

Now please check with the below code, see the image in corresponding div gets vertically aligned to center.

.galleryImg {
   display: table-cell;
   height: 60px;
   vertical-align: middle;
   width: 173px;
}

Hope it will help you.


Need Your Help

InternetExplorer COM document available in PowerShell ISE but not in regular PS console

internet-explorer powershell com scripting

The code below works in PowerShell ISE but when ran in regular PowerShell console, the document object is empty:

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.