Please see this codepen: https://codepen.io/allen-houng/pen/XGMjMr?editors=1100#0
<div>
<img src="https://res.cloudinary.com/djcpf0lmv/image/upload/v1549372650/Templates/yoga.jpg" data-radium="true" style=";">
<div class="description">
Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum.
</div>
</div>
I have a parent div with two child divs - an image and a description. I'm sizing the image according to viewport height which means the width would be dynamic and responsive. How would I size the corresponding sibling div .description
to match the image's width without javascript?
Make the container inline-block
then force the width of text to be 0
so the width of the container is defined by the image (the text doesn't contribute to the width) then force the width again to be 100%
using min-width
.parent {
background: pink;
display:inline-block;
}
img {
display: block;
max-height: 70vh;
}
.description {
width:0;
min-width:100%;
}
<div class="parent">
<img src="https://picsum.photos/id/1004/900/600">
<div class="description">
Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum.
</div>
</div>
The same trick work even without image where you need an element to be sized based on another one.
Example with text:
.parent {
background: pink;
display:inline-block;
}
.description {
width:0;
min-width:100%;
}
<div class="parent">
<h2>a title that will define the width</h2>
<div class="description">
Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum.
</div>
</div>
Another trick for the first example is to consider the ratio of the image to know the width you need to define:
.parent {
background: pink;
display:inline-block;
}
img {
display: block;
max-height: 70vh;
}
.description {
max-width:calc(70vh * 1.5);
}
<div class="parent">
<img src="https://picsum.photos/id/1004/900/600">
<div class="description">
Fusce consequat. Nulla nisl. Nunc nisl. Duis bibendum, felis sed interdum venenatis, turpis enim blandit mi, in porttitor pede justo eu massa. Donec dapibus. Duis at velit eu est congue elementum.
</div>
</div>