How to make an overlay that exactly covers an object-fit:contain image

77 Views Asked by At

Setup: I am provided a container div that can dynamically be any size and an image that can be any size. I want the image to always fit in the center of the container (with allowances for the container to have arbitrary padding).

Need: How can I make another div that exactly overlays the image while the image scales to fit maximally in the container? I can't think of any CSS technique that allows the image to grow/shrink in x and y to fit and my attempt at using ResizeObserver in React not only didn't work and caused infinite call-backs, but were extremely... "unparsimoniuous" with complicated hook usage.

I am also using Fluent UI React v9

const App = ()=>(
<div id="container">
    <img id = "image" src="https://baconmockup.com/100/200"/>
    <div id = "overlay"/>
</div>
 )
 

ReactDOM.render(<App/>, document.querySelector("#app"))
#container{
width:500px;
height:400px;
padding-left: 30px;
padding-bottom: 10px;
resize:both;
overflow:scroll;
}

#image{
width:100%;
height:100%;
object-fit:contain;
  box-shadow: inset 0 0 10px #0f0;
}

#overlay{
position:absolute;
border:6px red solid;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

 
 <div id="app"></div>

0

There are 0 best solutions below