Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vertically centre align a cropped image in a div

Tags:

I'm trying to create a CSS style that will take an image and scale it to best fit a letter box shaped div. The overflow will be cropped off. I'm close with this and it currently looks like this:

current appearance

The original image is

original image

I'd like to modify this so that the image is centered vertically in the div rather than top aligned. What am I missing here? My html is

.crop {
  width: 670px;
  height: 200px;
  overflow: hidden;
}

.crop img {
  width: 670px;
}
<div class='crop'>
  <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' />
</div>

I can't assume the height of the image to be the same everywhere I use this.

like image 461
Real World Avatar asked Jun 21 '17 21:06

Real World


People also ask

How do I center an image within 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.

How do I vertically center a div in my body?

Start styling the second <div>.Put the “middle” value of the CSS vertical-align property. It will align the vertical the box's vertical center with the baseline of the parent box plus half the x-height of the parent.


1 Answers

You can position the image relatively and then have the browser bump it upward 50% with top:-50%;:

.crop {
  width: 670px;
  height: 200px;
  overflow: hidden;
}

.crop img {
  width: 670px;
  position:relative;
  top:-50%;
}
<div class='crop'>
  <img src='http://cycle.travel/images/600/amsterdam_ccby_conor_luddy.jpg' />
</div>
like image 73
j08691 Avatar answered Sep 29 '22 20:09

j08691