14

I've decided to throw in the towel on this problem and need some help :). As per title trying to vertically align an image wrapped in an anchor element in the center of a floated fixed height div.

Done a lot of googling for solutions and the closet I can get is below when the div is not floated (however it needs to be). Any ideas would be greatfully appreciated!

.class_name {
/*float: left*/
width:153px; 
height:153px;
margin:3px;
padding:4px;
border:1px solid #dedede;
text-align: center;
vertical-align: middle;
background-color: #000;
display: table-cell;
}

<div class="class_name">
    <a href=""><img src="image.jpg" alt="" /></a>
</div>
John
  • 1
  • 13
  • 98
  • 177
Hayden
  • 141
  • 1
  • 1
  • 3

3 Answers3

21

Well, I bumped into the same issue last night (for a gallery-like type of thing), and managed to find a solution after stumbling onto this page. I'm happy to report this also seems to work for floated elements!

The trick is basically to give the outer element "display: table;", and the inner element (containing the img) "display: table-cell;".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html><head>
<style type="text/css">
.class_name {
    display: table;
    float: left;
    overflow: hidden;
    width: 153px; 
    height: 153px;
}

.class_name a {
    display: table-cell;
    vertical-align: middle;
    text-align: center;
}
</style>
</head>
<body>
    <div class="class_name">
         <a href=""><img src="image.jpg" alt="" /></a>
    </div>
</body>
</html>

For IE8, you do need to be in standards mode. Some additional positioning is needed to get it to work in IE7:

<!--[if lte IE 7]><style type="text/css">
.class_name {
    position: relative;
}
.class_name a {
    position: absolute;
    top: 50%;
}
.class_name img {
    position: relative;
    top: -50%;
    width: 100%;
}
</style><![endif]-->
Paul
  • 2,132
  • 15
  • 13
0

If the height is fixed and you know the size of the image, just position the image manually. Use position:absolute;top:25px; on the image or something like that, or add a margin to the image: margin:25px 0;.

mattbasta
  • 13,492
  • 9
  • 47
  • 68
0

There is a cross browser css solution for this available here: http://www.vdotmedia.com/blog/vertically-center-content-with-css/

Jamie
  • 1,340
  • 11
  • 22
  • Ah yes I came across this. Still same issue though when it's floated which very frustrating! – Hayden Sep 07 '10 at 03:30