7 Structure & Layout

36 Intrinsic sizing

The problem

As we all know, if we don’t set a specific height on an element, it automatically adjusts to its contents. What if we want a similar behavior for the width as well? For example, let’s assume we have HTML5 figures, with markup like the following:

HTML

<p>Some text […]</p><figure>    <img src="adamcatlace.jpg" />    <figcaption>        The great Sir Adam Catlace was named after        Countess Ada Lovelace, the first programmer.    </figcaption></figure><p>More text […].</p>

Let’s also assume we’re applying some basic styling to them, such as a border around the figures. By default, this looks like Figure 7.1. We want to make the figures as wide as the image they contain (which could vary in size) and center them horizontally. The current rendering is quite far from what we want: the lines of text are much longer than the image. How do we make the width of the figure determined by the width of the image it contains instead of the width of its parent?* Over the course of our career, we have probably built our own list of CSS styles that result in such width behavior, usually as a side effect:

image

FIGURE 7.1 The default way our markup is rendered, after a bit of CSS for borders and padding

  • Floating the <figure> gives us the right width, but also drastically alters the layout of the figure, in ways we might not want (Figure 7.2).

Get CSS Secrets now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.