Calculate the real height of the image using CSS variables without JavaScript

Viewed 33

I have a container with an image and text. In the mobile version I want h1 positioned absolutely over the image and in the desktop version I want .box positioned over the image.

...
<div class="container" style="--img-w:1280; --img-h:720">
  <img src="..." width="1280" height="720">
  <div class="box">
    <h1>Title</h1>
    <p>Lorem Ipsum...</p>
  </div>
</div>
...

The image is always 100% of the screen width.

The image as well as the content are different on each subpage, so I can't use position: absolute with bottom because the height of each element is different.

Therefore, the best way is to use top. That' s why I need to calculate the rendered height of the image. I am able to set CSS variables containing the dimensions or aspect ratio of the current image.

Rather, it is possible to do this with CSS variables and calc. Just how? The solution should be in CSS only.

.container{
  position: relative;
}

img{
  width: 100%;
  height: auto;
}

h1{
  position: absolute;
  /*⬇️???*/
  /*This is not working*/
  --width-ratio: calc(100vw / var(--img-w);
  /*Other calculations...*/
  /*Rendered image height minus 20px*/
  top: calc(var(...) ...)
  /*⬆️???*/
}

@media(min-width:768px){
  h1{
    position: static;
  }

  .box{
    position: absolute;
    bottom: 20px;
  }
}

Mobile: Mobile

Desktop: Desktop

0 Answers
Related