如何将元素放在<img/>标记之上的最佳方法?

时间:2015-07-20 10:00:27

标签: css html5

我有一张卡片列表,其中卡片的背景是图像,并且必须在其上方放置一些额外的信息。对于背景图像来说听起来不错?是的,但是因为我需要动态设置这些图像并且图像需要可编辑,所以背景图像不是一个选项(我知道有办法做到这一点,但它不适合这种特殊情况)

所以这就是我的卡片的样子

<figure>
<img src="foo.jpg" alt="">
<figcaption>
<h5>Name:<span>xyz</span></h5>
<h6>Location:<span>xyz</span></h6>
</figcaption>
</figure>

而css应该做什么,但它并没有,而且在我看来它似乎不是一个好的例程:

.container-of_the-cards{ /* This is actually a <li> element with some different specs, but for illustration purposes I guess this one is easier */
width:100%;
display:inline-block;}
figure{
box-sizing:border-box;width:30%;height:300px;margin-right:1.1%;overflow:hidden;}
figure img{
width:100%;
height:100%;}
figcaption{box-sizing:border-box;margin:0 20px; background: blue; margin-top:-280px;}
figcaption h5{top-margin:30px;}
figcaption h6{top-margin:80px;}

所以,现在我遇到了这个问题:

margin-top:-280px;

我宁愿阻止这种情况,但如何呢?

1 个答案:

答案 0 :(得分:0)

您应该添加position: relative以使元素不在流量中。

您需要调整左侧和顶部属性。

<强> HTML

<figure>
    <img src="foo.jpg" alt="">
        <figcaption>
            <h5>Name:<span>xyz</span></h5>
            <h6>Location:<span>xyz</span></h6>
        </figcaption>
</figure>

<强> CSS

.container-of_the-cards{ /* This is actually a li-element with some different specs, but for illustrational purposes I guess this one is easier */
    width: 100%;
    display: inline-block;
}
figure{
    box-sizing: border-box;
    width: 30%;
    height: 300px;
    margin-right: 1.1%;
    overflow: hidden;
}

figure img{
    width: 100%;
    height: 100%;
    position: relative;
}

figcaption{
    box-sizing: border-box;
    margin: 0 20px;
    background: blue;
    margin-top: -280px;
}

figcaption h5{
    top-margin:30px;
}

figcaption h6{
    top-margin:80px;
}

JSFIDDLE

如果这不是你想要的效果,请编辑你的问题以便更清楚。