Leff
Leff

Reputation: 1318

CSS - Image caption alignment not working

I have a html that looks like this:

                <div class="large-4 columns">
                    <div class="promo-box">
                        <a href="#">
                          <img src="/our-projects-sfk.png">
                          <div class="caption">
                            <h5><Våre prosjekter</h5>
                            <p>Hver sommer i 20 år har vi gledet familier som har et kreftrammet barn med tre-dagers drømmetur til Kristiansand Dyrepark.</p>
                          </div>
                        </a>
                    </div>
                </div>

Since I don't know the width of image in advance, I can't set a fixed width for the div and instead need div and caption to take the width of the image. I have tried everything, setting the promo-box to display: inline-block and also setting it to display: table and using figure and figcaption tags, but nothing worked. Not sure how can I set the caption to the width of the image?

This is was my attempt:

.promo-box {
  display: table;
}

.promo-box img {
  width: 100%;
  height: auto;
  vertical-align: top;
  margin-bottom: 3px;
}

.promo-box .caption {
  display: table-caption;
  caption-side: bottom;
  box-sizing: border-box;
  padding: 10px;
  margin: 0;
}

With this the end result was this:

enter image description here

Upvotes: 0

Views: 460

Answers (2)

Johannes
Johannes

Reputation: 67758

If your .promo-box is a table, you should make the image and the caption container table-rows, and assign text-align: center to the caption container.

Addition:

See this codepen: http://codepen.io/anon/pen/zNyQGQ

I also added a fixed with to the container - otherwise the image will always become as wide as the caption text.

ADDITION AFTER COMMENT:

Okay, then erase the width on the container and change the CSS of the caption to this:

.promo-box .caption {
  display: table-caption; /* changed */
  width: 100%; /* changed */
  box-sizing: border-box;
  padding: 10px;
  margin: 0;
  text-align: center;
}

See new codepen: http://codepen.io/anon/pen/LxMwBK

Upvotes: 1

Richard Parnaby-King
Richard Parnaby-King

Reputation: 14862

You want the text to be the same width as the image? You have that. You don't need any of the table or table-caption stuff.

Here, img and .caption have the same full width of .promo-box.

.promo-box {
  border: 1px solid red;
  width: 50%;
}
.promo-box img {
  width: 100%;
  height: auto;
  margin-bottom: 3px;
}
.promo-box .caption {
  margin: 0;
}
<div class="large-4 columns">
  <div class="promo-box">
    <a href="#">
      <img src="http://dummyimage.com/400x250">
      <div class="caption">
        <h5><Våre prosjekter</h5>
        <p>Hver sommer i 20 år har vi gledet familier som har et kreftrammet barn med tre-dagers drømmetur til Kristiansand Dyrepark.</p>
      </div>
    </a>
  </div>
</div>

Upvotes: 0

Related Questions