I want to display the top of the image with the bottom part of the image hidden. The overflow is hidden but instead of displaying the image from top down, the image is being cut through the middle with a small part of both the top and the bottom hidden. Is there a way to fix this with css or do I need to crop the image manually?
Here is my code relative to the image..
img {
width: 100%;
height: 350px;
object-fit: cover;
display: block;
}
I have tried different position types. I’m very new to making websites and can’t think of other things to try to try to fix the problem
2
Answers
Here is a way using a couple of
div
containers withoverflow-y:hidden;
andoverflow-y:scroll;
as well asobject-position:
to show you how to achieve this.The
div
with the red border shows you how to show only the top part of the image. Thediv
with the green border shows you the image scrolling so that you can verify for yourself which part of the image is actually being shown in the reddiv
.To adjust which part of the image is being shown, you need to change the value of:
object-position: 0px 0px;
to something like:
object-position: 0px -200px;
For more information, please refer to: object-position on MDN
Yes, you can do this with
object-position: top
.This snippet below demonstrates how it works. The first image is constrained only in its width, so the entire image is displayed in its intrinsic aspect ratio (square). The second image has a height constraint added, as well as
object-fit: cover
to specify automatic cropping. Note that the central part of the image is retained by default: the top and bottom edges are cropped. The third image hasobject-position: top
added to specify that we want the automatic croping to retain the top of our image.