Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

CSS:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

.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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading