Ronnie
Ronnie

Reputation: 11198

Vertically centering image

I know there are a ton of posts about this issue. After reading all them I feel like I am close, but it still isn't working for me.

HTML:

<div class="product">
  <div class="image">
    <a href="#">
        <img src="http://i.imgur.com/rthFtAb.jpg" />
    </a>
  </div>
</div>

CSS

.product {
    height:225px;
    min-height:225px;
    max-width:220px;
    background-color:#ff00ff;

}

.image {
    min-height:225px;
    display:table-cell;
    vertical-align:middle;
}

.image img {
    max-width:100%;
}

http://jsfiddle.net/SBqU5/

What am I doing wrong here?

Upvotes: 0

Views: 66

Answers (3)

skippr
skippr

Reputation: 2706

If you are able to define a width and height to your image, you can use `position: absolute'.

.image {
    position: relative;
    height: 100%;

}

.image img {
    width: 220px;
    height: 105px;
    position: absolute;
    top: 50%;
    left: 50%;
    margin-left: -110px;
    margin-top: -52px;

}

DEMO

Note that the negative left and top margins are half of their width and height, respectively.

Upvotes: 0

Jason
Jason

Reputation: 4159

Six methods for centering something vertically.Pick your poison. Your method would fall under the "Table" option.

http://www.vanseodesign.com/css/vertical-centering/

Line-height

<div id="parent">
    <img src="image.png" alt="" />
</div>

#parent {
    line-height: 200px;
}

#parent img {
    vertical-align: middle;
}

Table

<div id="parent">
    <div id="child">Content here</div>
</div>

#parent {display: table;}

#child {
    display: table-cell;
    vertical-align: middle;
}

Negative Margins

<div id="parent">
    <div id="child">Content here</div>
</div>

#parent {position: relative;}

#child {
    position: absolute;
    top: 50%;
    left: 50%;
    height: 30%;
    width: 50%;
    margin: -15% 0 0 -25%;
}

Stretching

<div id="parent">
    <div id="child">Content here</div>
</div>

#parent {position: relative;}

#child {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    width: 50%;
    height: 30%;
    margin: auto;
}

Equal Padding

<div id="parent">
    <div id="child">Content here</div>
</div>

#parent {
    padding: 5% 0;
}

#child {
    padding: 10% 0;
}

Floater Div

<div id="parent">
    <div id="floater"></div>
    <div id="child">Content here</div>
</div>

#parent {height: 250px;}

#floater {
    float: left;
    height: 50%;
    width: 100%;
    margin-bottom: -50px;
}

#child {
    clear: both;
    height: 100px;
}

Upvotes: 2

G-Cyrillus
G-Cyrillus

Reputation: 106058

if you use display:table-cell; and max-width; parent should be display:table; table-layout:fixed and width:xxpx. DEMO

.product {
    height:225px;
    width:220px;
    background-color:#ff00ff;
    display:table;
    table-layout:fixed;
}
.image {
    display:table-cell;
    vertical-align:middle;
}
.image img {
    max-width:100%;
}

Upvotes: 1

Related Questions