Skip to content
Advertisement

How to remove background layer of an when using object-fit: contain;

I am trying to make image viewer, which has overlay window with div in the center and inside the div an image that scales up and down on window resize that keeps its default ratio by using object-fit: contain; which is working ok. The problem is that when using object-fit: contain; it scales the content of the and the has someting like background layer which stops me from clicking on the overlay window so I can close the view. Is it possible to crop, cut auto resize the so it is always big as the content. Maybe using clip:rect();. Thanks in advance.

I am trying to remove the blue background so I can click on the background and close the overlay window, but still keep the ability to click on the image without closing the overlay.

enter image description here

Example: https://jsfiddle.net/qwdnkxLt/

JavaScript

Advertisement

Answer

Solution 1

Setting the position of any object to absolute is a little dangerous: it makes it ignore almost any relationship it has with other objects regarding position, scale etc.

As such, I would recommend using position: relative; for your image container and allowing one of the two dimensions (I recommend using height: 100% and width: inherit or auto) to scale automatically to maintain the aspect ratio. Modern browsers are smart enough to usually fill in the area given properly without leaving any gaps.
Also, remember to use margin: auto; to center your objects nicely.

This should solve your problem:

JavaScript

JSFiddle here: https://jsfiddle.net/uewog42m/25/

A final thought: it is easier to debug if you keep your CSS and HTML/JS separate! Consider using a separate stylesheet for all your CSS code.

Solution 2

Another way to approach this problem, is to use a container for the image and use it for the scaling. Then, place the image inside the container and use the parent’s dimensions. Last, cut the overflow (if any). Or if you don’t want to cut part of the image, don’t use max values for the width/height and center the image.

It should look something like this:

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement