如何将图像放在图像上?

时间:2014-02-27 13:11:09

标签: html css html5 css3

我正在为响应式网站工作。我想在大图像上放置一个小图像。小图像应该放在这个大图像的正中心。我不能把大图像作为我的页面的背景。它应该在div内。怎么样?

JSFIDDLE

//code
<div class="text-center">
    <img id="draggable1" class="img-responsive" src="http://photos.foter.com/a266/freestanding-wood-and-wire-pet-gate-size-21-width-narrow-span-2658163_300x300.jpg">
       <img class="heartimg" src="http://gorgeousme.co/media/19340/heart_50x42.jpg"/>
    </img>
</div>

4 个答案:

答案 0 :(得分:3)

在心脏上使用绝对定位img

JSFiddle Demo

<强> CSS

.text-center {
    display: inline-block;
    border:1px solid grey;
    position: relative;
}

.text-center img {
    display: block;
}

.text-center .heartimg {
    position: absolute;
    top:50%;
    left:50%;
    margin-top:-25px; /* half of it's height */
    margin-left:-21px; /* half of it's width */
}

答案 1 :(得分:2)

<img>元素不能包含其他元素。所以你不能做<img><img/></img>

之类的事情

将两个图片嵌套在相同的div下,并使用position: absolute;position: relative来对齐您的图片。

这是 Kitten-based example

HTML

<div class="text-center">
    <img class="largeImage" src="http://placekitten.com/g/500/600?ext=.jpg" alt="Large kitten"/>
    <img class="smallImage" src="http://placekitten.com/g/50/50?ext.jpg" alt="Tiny kitten"/>
</div>

CSS

.text-center {
    display: inline-block; /* Inline block to match large image dimensions */
    position: relative;
}

.smallImage {
    position: absolute;
    top: 50%;
    left: 50%;
    margin-top: -25px; /* Half the image's size. */
    margin-left: -25px;
}

答案 2 :(得分:0)

您可以使用 CSS位置来实现您的目标。

In MDN 您可以检索有关不同CSS位置及其用途的信息。

答案 3 :(得分:0)

根据您的小提琴,您可以添加以下css类,心脏图像将位于另一个图像之上:

.heartimg {
    position: relative;
    top: -55px;
    left: -55px
}

基本上通过定位“相对”,您可以相对于通常显示的位置移动心脏图像。这方面工作的一个例子是:http://jsfiddle.net/du84q/祝你好运!

注意:正如其他人所说,你也不应该嵌套“img”标签。浏览器倾向于忽略这一点,但它并不严格对你有好处。

相关问题