EN
HTML - img element as background instead of CSS background-image
1
answers
0
points
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
To imitate CSS background-image property with HTML <img> tag, you need to:
- set
position: relativetodivcontainer andabsoluteto theimg, - set
imgelementz-indexto be at least 1 lower than thedivcontainer, - disable
imgpointer events, - disable
divcontainer 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: coverwhich works likebackground-size: cover.
0 comments
Add comment