Reputation: 674
We have the following code on codepen. The problem we have is that we are using the <picture>
attribute to render images based on viewport
, but are not able to have the image take up the same amount of space as the text that is overlaid on image.
codepin details:
background-color: #eee
so you can see the area the text takes up. position: absolute
, but open to change it. viewport
, we always want the image from the <source>
tag to only take up what the text takes up.Goal:
<picture>
and <source>
style: background-image('path/to/image')
on <div class="item__img">
How can we have the image
expand as the text on top of it expands?
Upvotes: 0
Views: 909
Reputation: 5060
You coud use object-fit
property on your img:
.item {
position: relative;
width: 33%;
}
img{
position:absolute;
width:100%;
height:100%;
object-fit:cover;
}
.item__text {
background-color: #eee;
opacity: 0.5;
padding:32px;
}
<div class="item">
<div class="item__img">
<picture>
<source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature">
<source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature">
<img src="https://placeimg.com/640/480/nature" alt="Flowers">
</picture>
</div>
<div class="item__text">
<h3>Some title</h3>
<p>Efficiently communicate sticky quality vectors after compelling growth strategies. </p>
</div>
</div>
Upvotes: 2
Reputation: 715
If your image is always bigger than the textbox, here's a solution
.item {
position: relative;
max-width: 100%;
}
.item__img img {
width: 100% !important;
}
.item__text {
position: absolute;
background: rgba(238,238,238, 0.5);
padding: 32px;
top: 0;
right: 0;
bottom: 0;
left: 0;
z-index: 5;
display: flex;
flex-direction: column;
justify-content: center;
}
<div class="item">
<div class="item__img">
<picture>
<source media="(min-width: 1300px)" srcset="https://placeimg.com/1000/480/nature">
<source media="(min-width: 1024px)" srcset="https://placeimg.com/960/480/nature">
<img src="https://placeimg.com/640/480/nature" alt="Flowers" style="width:auto;">
</picture>
</div>
<div class="item__text">
<div>
<h3>Some title</h3>
<p>Efficiently communicate sticky quality vectors after compelling growth strategies. </p>
</div>
</div>
</div>
Upvotes: 0