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>
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.
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.
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.
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]-->
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With