I’m building a teaser component in HTML using an image and a title. So something like this:
<div>
<img src="./image.jpg" />
<h1 contenteditable>Blabla</h1>
</div>
I know the exact dimensions of the <div>
, but of course the text in the <h1>
might change. I want the text to get priority and so the image should automatically shrink when the text gets longer (the text should not disappear from the box). One solution would be to use position:absolute
on the text and position it over the image, but then the image gets cut off.
I found this solution using CSS grid:
div {
width: 300px;
height: 200px;
background: red;
padding: 10px;
display: grid;
grid-template-rows: 1fr auto;
overflow: hidden;
}
img {
width: 100%;
height: 100%;
object-fit: contain;
}
h1 {
margin-top: 10px;
overflow: auto;
}
And this works in Firefox:
But unfortunately it doesn’t in Chrome:
I’ve tried something else with Flexbox but that also doesn’t work. Of course i could use Javascript to dynamically alter the image height, but i really would like a responsive CSS solution.
I’ve put the code for this example in this codepen.