0

I am looking for a way to dynamically vertically center images inside a fixed height div. I can't make the image a background image. I will have a variety of height images ranging from 300x375 down to 300x240. My height of the inside div is going to be 240 and if the image is taller than 240 I want to center the image. So with one with the height of 375 it would crop of the top and bottom 76.5px. If it was 300 for height it would crop off 30px top and bottom.

I have tried a variety of methods but it seems when I get the larger image to crop correct the smaller ones get messed up.

I will try to work on getting a jsfiddle up but want to get it posted as I am guessing this is fairly simple even though I have been un able to find a solution.

2 Answers 2

2

You don't necessarily need to use js, try using flexbox.

HTML

<div id="root">
  <img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/a0/Circle_-_black_simple.svg/1024px-Circle_-_black_simple.svg.png">
</div>

CSS

#root {
  width: 300px;
  height: 240px;
  overflow: hidden;

  display: flex;
  flex-direction: column;
  justify-content: center;
}

#root > img {
  width: 300px;
  height: 375px;
}

https://codepen.io/jc3m-the-flexboxer/pen/deEvpM

Sign up to request clarification or add additional context in comments.

1 Comment

Better answer than mine.
0

Assuming an HTML layout of this

<div class="one">
  <img src="https://placeimg.com/300/375/any">
</div>
<div class="one">
  <img src="https://placeimg.com/300/240/any">
</div>

You can iterate through the divs and set the margin top of the image to a negative value of half the difference between 240 and the image height

$(document).ready(function() {
    $('.one img').each( function() {
    if( $(this).height() > 240 ) {
        var diff = ($(this).height() - 240) /2
      $(this).css('margin-top', (diff * -1) + 'px')
    }
  })
})

The divs need to be set to overflow hidden for this to work.

Fiddle: https://jsfiddle.net/calder12/29s5gnLq/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.