background image crop height when the screen is reduced

I have a div with a background image

<div class="blog-img" style="background-image: url('{{ $blog->imgUrl }}');"></div>

The problem is that I can’t render this image without setting the styles to a fixed height and width


.blog-img {
  width: 600px;
  height: 500px;
  background-size: 100% auto; 
  background-position: unset;
  background-repeat: no-repeat;

Everything outputs almost the way I need, but the only thing is the problem with the height. When I reduce the screen, I need to cut off the extra piece of the block, but this does not happen due to the fact that a fixed height is set

enter image description here

How can I make it so that when the screen is reduced, this piece that I selected on the screen is cut off?

>Solution :

You have two options as far as I see it:

  1. Set aspect-ratio on the div that matches the aspect ratio of your picture. This will make sure that for any width of the div it will have the height to match the aspect ratio of the picture so it won’t be stretched or cropped. make sure to use background-size:contain.
  2. Set background-size to cover so there will automatic crop on the image but it would fit all sizes of the div. Tip: you can adjust the background-position property to make sure the part that you care about most in the picture is visible for example center center.

If you just care about the picture being shown properly go with the second option. However, if you have content inside that div or the size of the div is not under your control go with the first.

Leave a Reply