Languages

HTML - img element as background instead of CSS background-image

0 points
Asked by:
Elias999
819

How can I use the HTML <img> tag as the element's background instead of CSS background-image property?

I need to have two elements like:

<!doctype html>
<html>
<body>
  <div>
    <img src="path/to/image.jpg" />
    <p>
      some text...
    </p>
  </div>
</body>
</html>
1 answer
0 points
Answered by:
Elias999
819

To imitate CSS background-image property with HTML <img> tag, you need to:

  • set position: relative to div container and absolute to the img,
  • set img element z-index to be at least 1 lower than the div container,
  • disable img pointer events,
  • disable div container scroll,
  • set img size to 100% of the container,

Practical example

// ONLINE-RUNNER:browser;

<!doctype html>
<html>
<head>
  <style>

    div {
        position: relative;
        width: 100%;
        display: inline-block;
        overflow: hidden;
    }

    img {
        position: absolute;
        width: 100%;
        height: 100%;
        pointer-events: none;
        z-index: -1; /* at least one less than the div. */
        /* object fit: cover; */
    }

    p {
        color: white;
        padding: 25px;
    }

  </style>
</head>
<body>
  <div>
    <img src="https://dirask.com/static/bucket/1631892380910-mbQLq3JYJX--background-h400-w600.jpg" />
    <p>
      Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed elementum purus elit, ac sodales ipsum iaculis interdum. Duis rutrum eu massa vel laoreet. Nulla nec suscipit nisi. Ut mattis libero eu finibus hendrerit. Maecenas et egestas augue. Mauris et velit iaculis, dictum sem sodales, lacinia neque.
    </p>
  </div>
</body>
</html>

Note:

For the img style, you can optionally use object-fit: cover which works like background-size: cover.

0 comments Add comment
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join