user2794426
user2794426

Reputation:

How to place image over image?

I am working for responsive site. I want to place a small image over large image. Small image should be placed exactly center of this large image. I can't take large image as background of my page. It should be inside div. How?

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>

Upvotes: 2

Views: 270

Answers (4)

Madara&#39;s Ghost
Madara&#39;s Ghost

Reputation: 174957

The <img> element cannot contain other elements inside. So you can't do something like <img><img/></img>

Nest both images under the same div and use position: absolute; and position: relative to align your image.

Here's a 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;
}

Upvotes: 2

Paulie_D
Paulie_D

Reputation: 114991

Use absolute positioning on the heart 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 */
}

Upvotes: 3

drew_w
drew_w

Reputation: 10430

Based on your fiddle, you can add the following css class and the heart image will be on top of the other image:

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

Basically by positioning "relative" you can move the heart image relative to where it normally would have shown. An example fiddle with that working is here: http://jsfiddle.net/du84q/ Best of luck!

Note: As others have noted you shouldn't be nesting the "img" tag either. Browsers tend to ignore this, but it doesn't strictly do you any good.

Upvotes: 0

Arkana
Arkana

Reputation: 2889

You can use CSS position to achieve what you want.

In MDN you can retrieve information about different CSS position and its uses.

Upvotes: 0

Related Questions