Home > Software design >  Crop an image to zoom in to only part of that image inside a div
Crop an image to zoom in to only part of that image inside a div

Time:11-09

Is there a way to use CSS to get only a specific part of an image to appear as a div background? Basically like cropping?

This image from adobe pretty much sums up what I mean and what I wish I could do with divs:

I want to use images from the web as background images for divs of specific size (banners for instance). However, most googling takes me to

What would be the way to do that? It's something I'm used to being able to do very easily with most image-editing interfaces (adobe, most social media image editing tools), but I'm finding it very hard to do with CSS. Most googling brings me to things like object-position, or background-size, or object-fit, but all of them assume you want the whole image. I'd love if there was a way to just have a PART of the image visible in your div container.

CodePudding user response:

I think the property you are looking for is background-position. By defining the width and height of your div you define the size/dimensions of your crop area. Then using the background-position property you can move that crop area around.

Here's an example:

.cropped {
  width: 128px;
  height: 128px;
  background-position: 0 100%;

  background-image: url("https://source.unsplash.com/512x256?city");
  position: absolute;
  bottom: 0;
}

.full {
  background: linear-gradient(
      rgba(255, 255, 255, 0.5),
      rgba(255, 255, 255, 0.5)
    ),
    url("https://source.unsplash.com/512x256?city");
  width: 512px;
  height: 256px;
  position: relative;
}
<div >
  <div ></div>
</div>

  • Related