Onyx
Onyx

Reputation: 5772

How to restrict how much of an image will be shown if the height is too big?

Imagine you have a 400 width 800 height image, however, you want the image to fill a 400 width x 400 height container BUT you don't want to scale it down, rather you want to slice off ( not display ) the bottom 400px of the image. How can I do that?

Upvotes: 0

Views: 42

Answers (2)

G-Cyrillus
G-Cyrillus

Reputation: 105863

Object-fit seems to be what you look for. it can clip or scale down the image.

values that can be used :

object-fit: fill;
object-fit: contain;
object-fit: cover;
object-fit: none;
object-fit: scale-down;

you may also use objec-position to set how to clip it.(if not specified, clipping is usually made from every side, showing the center) possible values.

object-position: center top;
object-position: 100px 50px;

examples using a 400x800 pixels image that should not exceed 50%'s height of viewport.

img {
width:400px;
max-height:50vh;
object-fit: cover;
}
img + img {
object-position: top left;
}
<img src="http://dummyimage.com/400x800">
<img src="http://dummyimage.com/400x800">

see https://caniuse.com/#search=object-fit to checkout which browsers understands it.

Upvotes: 1

Salvatore
Salvatore

Reputation: 1435

A quick way to get this done is to have the image inside a div of 400x400 and then hide the overflow content.

Useful links : Overflow css property

.image-holder {
  height: 400px;
  width: 400px;
  overflow: hidden;
}
<div class="image-holder">

  <img src="https://images.pexels.com/photos/236047/pexels-photo-236047.jpeg?cs=srgb&dl=landscape-nature-sky-236047.jpg&fm=jpg" alt="Image unavailable" />

</div>

Upvotes: 1

Related Questions