垂直居中对齐图像上的图形

时间:2016-03-08 11:31:09

标签: html css html5 css3 flexbox

我正试图以一种居中的方式在图像上对齐figcaptionresult desired

到目前为止,我有以下代码:

.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;
}

对于以下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>

问题是,以中心为例,我正在使用left: -20px;,这肯定不是那么敏感。任何的想法?感谢

2 个答案:

答案 0 :(得分:2)

Flexbox可以做到这一点。你不需要使用相对(或绝对)定位。

  • 将整个figure元素设置为具有column - 方向的灵活容器。
  • 使用align-items: center将图像和标题居中。
  • 使用flex order属性切换图像和标题的顺序。

&#13;
&#13;
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; */
}
&#13;
<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>
&#13;
&#13;
&#13;

答案 1 :(得分:2)

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>