Formatting image and caption

It seemed to be a simple change! I simply want to put an image within a div with a dark background and add a caption. My markup is:

<div class="photo" style="width:660px">
  <img src="fox-lane/fox-lane1.jpg" alt="A Very Early View (before the road was made up)" width="640" height="483">
  <p class="caption">A Very Early View (before the road was made up)</p>
</div>

and my CSS

.photo {
    background: #666;
    text-align: center;
    padding: 10px;
}
.photo img {
}
.photo p {
    background: white;
    padding: 5px 0;
}

and I have attached the result. There seems to be more padding to the left and right of the image than 10px; it seems to be 10px to the top. I have tried changing the padding and margin on each element but I’m just driving myself nuts!

Change width of your div to 640px
Default box model calculates total width of element as WIDTH + PADDINGS + MARGINS
i.e. now your div is 680px (660 + 10 + 10) wide, while you’re expecting it to be 660px

Or, apply this rule to your div:

box-sizing: border-box;

This will change CSS box model to another one, which doesn’t include paddings and margins into elements size

Something like this is a possibility:

.photo {
    display:table;
    background: #666;
    padding: 10px;
    margin:0 auto;
}
.photo img {
    display:block;
}
.photo p {
    background:white;
    text-align:center;
    padding: 5px 0;
    margin:10px auto 0;
}
<div class="photo">
  <img src="http://placehold.it/640x483" alt="A Very Early View (before the road was made up)" width="640" height="483">
  <p class="caption">A Very Early View (before the road was made up)</p>
</div>

ninja’d by @megazoid :slight_smile:

Ah - thanks for the explanation @megazoid and for the ninja :slight_smile: Much appreciated.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.