In the process of constructing a teaser element using HTML, I plan to integrate an image and a title. This is what I have in mind:
<div>
<img src="./image.jpg" />
<h1 contenteditable>Something</h1>
</div>
While the dimensions of the <div>
are fixed, the length of the text within the <h1>
may vary. It's important that the text takes precedence, causing the image to automatically resize when the text extends (without overflowing from the box). While one solution involves using position:absolute
for the text to overlay on the image, this leads to cropping of the image.
A workaround utilizing CSS grid has been discovered:
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;
}
This method functions properly in Firefox:
https://i.sstatic.net/oz8jpUA4.png
However, it encounters issues in Chrome:
https://i.sstatic.net/6Hsom4MB.png
Attempts with Flexbox were unsuccessful as well. Although JavaScript could adjust the image's height dynamically, I'm inclined towards a responsive CSS solution.
You can access the code for this specific example through this CodePen link.