Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

<p> element inheriting width from a centered <img> above it

Tags:

html

css

Let's say that I have an image that can be a variable width (min:100px, max:100% [760px]). I also have a <p> element that is to be shown right below the image. I'd like the <p> to end up with the same width as the <img>, but I can't seem to find an answer.

Here is the code involved in such a scenario jsfiddle:

html:

<div id='page'>
    <figure>
        <img src='http://www.myimage.com/img.jpg'/>
        <p>Hi there. I am some text. I would like to start where the image starts :(</p>
    </figure>
</div>

css:

#page {
    width:760px; /* arbitrary */
}

figure img {
    display: block;
    border: 1px solid #333;
    max-width: 100%;
    min-width: 100px;
    margin: 0 auto;
}

figure p {
    /* ??? */
}

Any ideas?

like image 273
a.real.human.being Avatar asked Nov 01 '22 06:11

a.real.human.being


1 Answers

You can use display: table on the figure and set a small width on it. Because it's a table layout it'll then become as wide as the content, in this case the image.

figure {
  display: table;
  width: 1%;
}

Demo

like image 58
davidpauljunior Avatar answered Nov 15 '22 11:11

davidpauljunior