Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS - vertically center an image within a floated div

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>
like image 827
Hayden Avatar asked Sep 07 '10 02:09

Hayden


People also ask

How do I center an image in a div in CSS?

Step 1: Wrap the image in a div element. Step 2: Set the display property to "flex," which tells the browser that the div is the parent container and the image is a flex item. Step 3: Set the justify-content property to "center." Step 4: Set the width of the image to a fixed length value.

How do you center an image to float in CSS?

The CSS float property is used to set or return the horizontal alignment of elements. But this property allows an element to float only right or left side of the parent body with rest of the elements wrapped around it. There is no way to float center in CSS layout.

How do I vertically center a div element?

Center Vertically - Using line-height Another trick is to use the line-height property with a value that is equal to the height property: I am vertically and horizontally centered.


1 Answers

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]-->
like image 63
Paul Avatar answered Oct 30 '22 14:10

Paul