简体   繁体   中英

Vertically center-align a figcaption on an image

I'm trying to align a figcaption over an image, in a centered way: 想要的结果

So far, I have the following code:

.portfolio-item figcaption{
    position: relative;
    top: -40px;
    left: -20px;
    width: 280px;
    background: rgb(52,152,219);
    color: white;
    display: flex;
    flex-direction: row;
    justify-content: space-around;
    padding: 10px 5px 10px 5px;
}

For the following HTML:

<!-- PORTFOLIO IMAGE 1 -->

<div class="portfolio-item">
    <figure>
        <img  src="assets/img/portfolio/folio01.jpg" alt="">
        <figcaption>
                <h5>UI DESIGN</h5>
                <a data-toggle="modal" href="#myModal" >Take a Look</a>
        </figcaption>
    </figure>
</div>

The problem is, to center it, I'm using left: -20px; which is definitely not that responsive. Any idea? Thanks

Flexbox can do this. You don't need to use relative (or absolute) positioning.

  • Make the entire figure element a flex container with column -direction.
  • Center both image and caption with align-items: center .
  • Switch the order of the image and caption with the flex order property.

 figure { display: flex; flex-direction: column; align-items: center; } .portfolio-item figcaption { order: -1; /* default value for all flex items is 1 */ display: flex; flex-direction: row; justify-content: space-around; width: 280px; background: rgb(52, 152, 219); color: white; padding: 10px 5px 10px 5px; /* REMOVED position: relative; top: -40px; left: -20px; */ } 
 <div class="portfolio-item"> <figure> <img src="http://i.imgur.com/60PVLis.png" width="100" height="100" alt=""> <figcaption> <h5>UI DESIGN</h5> <a data-toggle="modal" href="#myModal">Take a Look</a> </figcaption> </figure> </div> 

 figure { position: relative; height: 400px; border: 1px dashed red; } figure > img { position: absolute; left: 50%; /* horizontal alignment */ transform: translateX(-50%); /* horizontal alignment (fine tuning) */ z-index: -1; /* keep image under figcaption always */ } figure > figcaption { position: absolute; top: 40%; /* vertical alignment */ left: 50%; transform: translateX(-50%); display: flex; flex-direction: row; justify-content: space-around; width: 280px; background: rgb(52, 152, 219); color: white; padding: 10px 5px 10px 5px; } 
 <div class="portfolio-item"> <figure> <img src="http://i.imgur.com/60PVLis.png" width="200" height="200" alt=""> <figcaption> <h5>UI DESIGN</h5> <a data-toggle="modal" href="#myModal">Take a Look</a> </figcaption> </figure> </div> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM