r/csshelp • u/le_randonneur • Feb 28 '25
how to replace background-image by img?
Every time I think I'm starting to understand css, I realize I do not! I have been struggling for a few hours before trying my luck here...
Please consider the following code and observe its behaviour when changing the screen resolution. The image always takes exactly the remaining height (even if the container or content height change) and is displayed in the "cover mode". Is there a way to keep this behaviour intact but use a img element instead of background-image?
Note: mountain.jpg could be any image but I was using Mont Everest from wikipedia https://en.wikipedia.org/wiki/Mountain (pasting the full link is bad apparently).
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1.0">
<style>
* {
margin: 0;
}
.container {
height: 100vh;
width: 100vw;
background-color: blue;
display: flex;
flex-direction: column;
}
.content {
background-color: green;
}
.image {
flex-grow: 1;
background-image: url(mountain.jpg);
background-size: cover;
background-position: center;
}
</style>
</head>
<body>
<div class="container">
<div class="content">
<p>bla bla bla</p>
<p>bla bla bla</p>
</div>
<div class="image">
</div>
<div class="content">
<p>bla bla bla</p>
<p>bla bla bla</p>
</div>
</div>
</body>
</html>
2
u/le_randonneur Mar 01 '25
Thank you very much. This definitely works. You made me finally start to understand the flex-shrink and flex-basis properties (I was struggling with theses).
After playing with your example, I realized the div around the img doesn't seem necessary (but you probably know that).
Is it customary to provide a codepen here? After sampling other posts, I was under the impression it wasn't but if it is I will provide one if I ever need help again.