Steven Trooster
Steven Trooster

Reputation: 21

Vertical align an image in div

I have a div container with a fixed height. The image in the div can be lager than de height of the div. The width of the image is set to 100% of the div. I would like to the image to be vertically centered; now the top of the image is shown, which sometimes can create a strange looking crop.

The html is:

<div class="itemImageBlock" style="/* padding:0px; */">
      <span>
        <a class="modal" rel="{handler: 'image'}" href="/media/k2/items/cache/23ac69ecf90d97d87602b5da326dea8e_XL.jpg" title="Klik om afbeelding te bekijken">
            <figure>
                <img src="/media/k2/items/cache/23ac69ecf90d97d87602b5da326dea8e_L.jpg" alt="Bootleg Betty" style="width:100%; height:auto;">
            </figure>
        </a>
      </span>

  </div>

And the css is:

div.itemImageBlock {
    padding: 0px;
    margin: 0 0 16px 0;
    height: 450px;
    overflow: hidden;
}

I've tried to use display: table-cell; but then I loose the height and get a full image. (that is the overflow: hidden is lost)

Upvotes: 2

Views: 76

Answers (2)

Chase
Chase

Reputation: 2304

try this:

.yourClass {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}

You can read about this more here.

Edit: As pointed out in the comments, this method must be applied to a div not a span, so either replace the span with a div, or wrap it in a div.

Upvotes: 1

Marc Audet
Marc Audet

Reputation: 46825

Here is one way of doing it using the CSS3 transform function translate and some absolute positioning.

On the parent container, set the height value and position: relative.

The child container span is then absolutely positioned with the top at 50% from the top edge of the parent.

You can then use transform: translateY(-50%) to move the span/image to the center of the parent block.

Using overflow: hidden hides the top and bottom portion of the image.

If the image height is short enough, the top/bottom space takes on the background color (or image) as the case may be.

div.itemImageBlock {
    border: 1px dotted blue;
    height: 350px;
    position: relative;
    overflow: hidden;
}
div.itemImageBlock span {
    position: absolute;
    width: 100%;
    top: 50%;
    transform: translateY(-50%)
}
div.itemImageBlock img {
    width: 100%;
    vertical-align: top;
}
figure {  /* Optional reset */
    margin: 0;
    padding: 0px;
}
<div class="itemImageBlock"> 
    <span>
        <a href="">
            <figure>
                <img src="http://placehold.it/500x800" >
            </figure>
        </a>
      </span>
</div>

Upvotes: 1

Related Questions