3

I'd like to write HTML to align an image caption in the centre relative to the image.

I'd like to align the image and the caption together to the left.

This should be true whatever the width of the containing element.

This is what I have so far:

[unknown containing element]
<div style="align: left; text-align:center;">
<img src="white.jpg" height="31px" width="200px" />
<span>Some caption text</span>
</div>
[/unknown]

But it's aligning the caption text centre relative to the containing element.

What do I need to fix?

Thanks!

AP257
  • 89,519
  • 86
  • 202
  • 261

3 Answers3

4

If you really mean relative to the image, make the caption element as wide as the image, then center the text. To be able to set a width on the caption element it needs to be a block element, so I changed it from to :

<div style="align: left; text-align:center;">
    <img src="white.jpg" height="31px" width="200px" />
    <div class="caption">Some caption text</div>
</div>

.caption {
    width: 200px;
    text-align: center;
}

You might set the width with inline CSS if that is easier.

<div style="align: left; text-align:center;">
    <img src="white.jpg" height="31px" width="200px" />
    <div class="caption" style="width: 200px">Some caption text</div>
</div>

.caption {
    text-align: center;
}
0

Center image caption in image

.container {padding:0.1em}  
.display-container {position:relative; width:50%}

.display-middle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%,-50%);
  -ms-transform: translate(-50%,-50%)
}

img {width: 100%;}
    <div class="container">     
      <div class="display-container">   
      
        <img src="http://lorempixel.com/400/200/sports/10" />       
        <div class="display-middle">
          <p>strikee .. !</p>
        </div>
       
      </div>     
    </div>
antelove
  • 3,216
  • 26
  • 20
0

You'll need to make the <span> act like a block element.

Take a look at this: http://jsfiddle.net/szNvt/

Alex
  • 8,875
  • 2
  • 27
  • 44
  • Also i may have miss read your question the first time, maybe this is more what you require: [http://jsfiddle.net/szNvt/1/](http://jsfiddle.net/szNvt/1/) – Alex Feb 18 '11 at 16:55
  • Isn't span with display:block a div? :) – stecb Feb 18 '11 at 16:59
  • sure. What i was trying to do was use the users code. There may have been a specific reason they wanted it to be a span. – Alex Feb 18 '11 at 17:01
  • Yes it was just to point that out.. to also let the questioneer know it ;) – stecb Feb 18 '11 at 17:05
  • Hi @Alex, this is very close, thanks! But is there a way to float the image left, with the caption centered relative to the image? – AP257 Feb 18 '11 at 17:05
  • Check my first comment is that what you require? – Alex Feb 18 '11 at 18:19