Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to hide extra top and bottom of an image inside its container?

Tags:

html

css

What I mean is that there's an image with dimensions W: 200px, H: 300px. It is inside an inline-block element div. The height and width of div are 200px, 200px. So there's 100px of extra part of the image, which is flowing out of the div, in vertical direction. I don't want to change the dimensions of the image. I just want to vertically align that image in the middle of div, that means equal portions of image from top and bottom would be out of the div. And later I want to hide those extra parts. Example:

<div id="body">
 <div id="container">
  <img src=""/>
 </div>
</div>

Any solution? Using CSS?


2 Answers

Use transform: translateY(); and overflow: hidden.

.container {
  display: inline-block;
  width: 200px;
  height: 200px;
  border: 2px solid red;
  overflow: hidden;
}
.container img {
  position: relative;
  top: 50%;
  transform: translateY(-50%);
}
This <img src="http://lorempixel.com/200/300/animals/5"/> become this
<div class="container">
  <img src="http://lorempixel.com/200/300/animals/5"/>
</div>

As you use fixed width/height on your div's, here is a great tips using the background property and still set the image source in the markup, as done with images.

A solution like this will center and crop any sized image.

.container {
  display: inline-block;
  width: 200px;
  height: 200px;
  border: 2px solid red;
  background: center center / cover;
}
These becoms like this<br>
<div class="container" style="background-image: url(http://lorempixel.com/200/300/animals/5)">
</div>
<div class="container" style="background-image: url(http://lorempixel.com/400/200/animals/7)">
</div>
<div class="container" style="background-image: url(http://lorempixel.com/400/600/animals/3)">
</div>

<br>which originally looks like this<br>

<img src="http://lorempixel.com/200/300/animals/5">
<img src="http://lorempixel.com/400/200/animals/7">
<img src="http://lorempixel.com/400/600/animals/3">
like image 55
Asons Avatar answered Oct 27 '25 14:10

Asons


Add an overflow:hidden to the .container which wraps the <img> and give the .container a position:relative. Then give the Image a position:absoulte relative to the .container.

After this move the Image 50px to the top, relative to the .container to vertically center the <img>.

Here is a working Fiddle: https://jsfiddle.net/87gjtje6/3/

.container {
  width:200px;
  height:200px;
  border:solid 5px red;
  overflow:hidden;
  position:relative;
}

.container img {
    width:200px;
    height:300px;
    top:-50px;
    position:absolute;
}
<div class="container">
  <img src="http://dummyimage.com/200x300/000/fff">
</div>
like image 20
bobbybackblech Avatar answered Oct 27 '25 14:10

bobbybackblech



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!