I have already several days looking for a solution CSS or component for making an image resizable (height and width) and over the image, elements keeping the position over the same X and Y coordinates of the image.
A simple code what I tried:
.img-container {
position: relative;
width: 100%;
height: 100vh;
background-color: antiquewhite;
}
.aspect-ratio-img {
width: 100%;
height: 100%;
object-fit: contain;
}
.overlay {
position: absolute;
top: 30%;
left: 30%;
}
<div class="img-container">
<img src="img.jpg" class="aspect-ratio-img" alt="Your Image">
<div class="overlay">Element</div>
</img>
</div>
But this is wrong. In the example, the "element" text should have been kept over the same column and row of the grid. But as I show in the image it maintains the Top and Left relative to the browser edge and not based on the position of the image
What would like to have is something like next gif:
- Background image maintains proportions and resize horizontally and vertically with the browser window
- Foreground elements keep the position in the same X,Y coordinates of the background image.And also resizes (like using transform)
If I find the solution, I will post it here.
2
Answers
I did a component with a slot which all you place there will be resized. I'm not using JQuery, but I use the library vue3-resize, you can also implement it without this library due to the VUE3 observer feature
Use:
This is pretty easy with grid – you can style the grid any way you like but here I "super centered" it and used an area name to put both elements at the same grid quadrant then used negative margins to move the text a bit.
I changed the layout to put the div outside the image to further illustrate placement of that element vs "flow" where it would normally be below.
Keep in mind for this example the image will scale a bit but that is just style which can be set with size, aspect ratio etc.
NOTE: if you truly want a "grid" you can set the background of the container then set rows/columns on the grid of the size you wish then place the text in any grid cell you wish.