'absolute positioning with respect to scalable element
In the following example code I have an outer div ("div1", relative position), which has viewport size. Inside there is a img which is scaled as large as possible, but not larger as the viewport. The two inner div ("div2" and "div3") are absolutely positioned with respect to the outer div ("div1").
Now I want to get the following: I want the "div3" to be aligned abolutely with respect to the img, i.e. at the left edge of the img, not at the left edge of the "div1". Putting the img and the "div3" inside another div does not work, because the viewport-size of the img will be destroyed.
Has anyone an idea how so solve this without using javascript?
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body style="margin:0px">
<div id="div1" style="width:100%;height:100vh;position:relative;align-items:center;justify-content:center;text-align:center;">
<div id="div2" style="position:absolute;left:0%;top:0%;background-color:lightgreen;">absolute with respect to viewport</div>
<img src="https://images.pexels.com/photos/2246476/pexels-photo-2246476.jpeg" style="max-height:100%;max-width:100%;"></img>
<div id="div3" style="position:absolute;left:0%;top:50%;background-color:lightcoral;align-items:center;justify-content:center;text-align:center;">absolute with respect to picture</div>
</div>
</body>
</html>
Solution 1:[1]
I just turned the css into the style option to shorten the example.
Thanks for the help. display:flex worked well.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Fabian Teichert |
