Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS "crop" images, but align in center vertically

Tags:

html

css

image

I'm currently cropping images with CSS as so:

<div class="crop">
    <img src="image.png" alt="">
</div>

.crop {
width: 150px;
height: 150px;
overflow: hidden;
}
.crop img {
width: 150px;
height: auto;
margin: 0 0 0 0;
}

This way, it aligns the image within the container horizontally. However, I have no idea how to align the image vertically in the center (so it's right in the middle). Any help?

like image 302
user3681788 Avatar asked Jan 10 '23 06:01

user3681788


2 Answers

/* Just gonna leave this here.. */

.crop {
    position: relative;
    overflow: hidden;
    height: 180px;
    margin: 8px;
}
.crop img {
    position: absolute;
    left: 50%;
    top: 50%;
    -webkit-transform: translate(-50%,-50%);
    -ms-transform: translate(-50%,-50%);
    transform: translate(-50%,-50%);
}
like image 110
Nikolay Sergeevich Avatar answered Jan 19 '23 16:01

Nikolay Sergeevich


Use these classes :


.center-crop-img {
  object-fit: none; /* Do not scale the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-cover {
  object-fit: cover; /* cover image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-contain {
  object-fit: contain; /* contain the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

.center-crop-img-scale-down {
  object-fit: scale-down; /* scale-down the image */
  object-position: center; /* Center the image within the element */
  width: 100%;
}

like image 20
smarteist Avatar answered Jan 19 '23 17:01

smarteist