html – How can I align text directly beneath an image?

html – How can I align text directly beneath an image?

Your HTML:

<div class=img-with-text>
    <img src=yourimage.jpg alt=sometext />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

You can use HTML5 <figcaption>:

<figure>
  <img src=img.jpg alt=my img/>
  <figcaption> Your text </figcaption>
</figure>

Working example.

html – How can I align text directly beneath an image?

In order to be able to justify the text, you need to know the width of the image. You can just use the normal width of the image, or use a different width, but IE 6 might get cranky at you and not scale.

Heres what you need:

<style type=text/css>
#container { width: 100px; //whatever width you want }

#image {width: 100%; //fill up whole div }

#text { text-align: justify; }    
</style>

 <div id=container> 
     <img src= id=image /> 
     <p id=text>oooh look! text!</p> 
 </div>

Leave a Reply

Your email address will not be published.