Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial


Michiel Visser
Michiel Visser
1,169 Points

Create image with text above, with variable wrapper width

Consider the following requirement for an html/css page:

  • A wrapper containing an image and text above the image (both within the wrapper)
  • The text could contain a link
  • The height of the wrapper is a percentage of its containing element, say 20%
  • The height of the image should be the height of the wrapper minus the height taken by the text above it. The length of the text is unknown at the time of coding.
  • The width of the image should be auto, to maintain aspect ratio
  • The width of the wrapper should be equal to the width of the image
  • The width of the text div should not exceed the width of the image. If the text is longer, the text should wrap on multiple lines

I have produced the following code, which works alright if the text is short, not exceeding the width of the image. But it doesn’t work if the text is longer (the text does not wrap and the width of the text div exceeds the width of the image). What would be a good solution for this?

  html, body {
    height: 100%;
  .wrapper {
    border: 2px solid red;
    display: inline-block;
    height: 20%;
  img {
    width: auto;
    height: calc(100% - 1em);
    display: block;
  .contents {
    font-size: 1em;
    line-height: 1em;
<div class="wrapper">
  <div class="contents">This is some text with unknown length with a <a href="#">link</a>.</div>
  <img src="http://via.placeholder.com/150x150" />

1 Answer

Flor Antara
Flor Antara
12,372 Points

Hi Michiel,

Although the task looks a little confusing, you should be able to solve your issue by giving the wrapper a width, and also preventing overflowing.

max-width: 100px;
overflow: hidden;
Michiel Visser
Michiel Visser
1,169 Points

Yes I know, it's a bit complex to describe. I don't want to use max-width or fixed width on the wrapper or any other element, since the width of the wrapper should be the width of the image. And the width of the image should be auto, where the height of the image is given as specified.