usernameabc
usernameabc

Reputation: 674

How to expand image as text overlay expands?

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:

  1. currently the text has background-color: #eee so you can see the area the text takes up.
  2. Image and text have position: absolute, but open to change it.
  3. based on the viewport, we always want the image from the <source> tag to only take up what the text takes up.

Goal:

  1. make image take up the same height and width as the text overlaid on top
  2. use <picture> and <source>
  3. not use style: background-image('path/to/image') on <div class="item__img">
  4. open to cropping image to make it fit, but would prefer it be done without the cropping.

Current issue: curernt issue

Desired output desired output

How can we have the image expand as the text on top of it expands?

Upvotes: 0

Views: 909

Answers (2)

ReSedano
ReSedano

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

buhbang
buhbang

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

Related Questions