Rayjax
Rayjax

Reputation: 7784

CSS - Put an image centered on top of another

I have got to make a page with an image with width 100% which will be at the top of the page (I will call this one "img1").

Over img1, i have to put another image which i will call "img2", which will have a fixed size in px and will be centered.

img2 will be the background of a form, so then I'll put a form on it.

I have already read some posts on how to put an image on the top of another with relative and absolute nested divs, but then I can't use a margin auto; on img2, because it has an absolute position, and because it has a size in px, i can't even put a left in %, because it would move depending on the screen size.

I have tried another option which is using two nested divs with background-images with specified background-sizes (100% width for img1 and 500px width for img2), and centering img2 with background-position : it works, but then the div of img1 (which is empty of course, because I'm using a background-image), has no height.

When I was using an tag, by putting 100% width on img1, the height was automatically defined because of the image ratio. But now with background-images I can't tell the div "hey, fit your height to the one your background-image please".

What do you suggest ? I hope I have well explained my problem.

Thank you very much

Upvotes: 1

Views: 8179

Answers (3)

Andy
Andy

Reputation: 14575

You can do it with CSS3 multiple background images

This allows you to specify more than one background like so:

background-image: url(http://i153.photobucket.com/albums/s223/chibizim/110-baby-monkey.png), url(http://upload.wikimedia.org/wikipedia/commons/e/e6/Standing-stone-state-forest-tn1.jpg);

DEMO

Upvotes: 1

mddw
mddw

Reputation: 5590

I don't understand this :

on img2, because it has an absolute position, and because it has a size in px, i can't even put a left in %, because it would move depending on the screen size.

You said img2 has a fixed size, it seems to me it's the perfect case for a centering with absolute position and negative margin.

Let's say your img2 is 200px wide :

.img2 {
  position: absolute;
  top: 0px;
  left: 50%;
  margin-left: -100px /* negative half the width */
}

It would not work if img2 had a % size.

Upvotes: 4

Da Pri
Da Pri

Reputation: 63

Try having your base image absolute and the picture that should go on top as relative, at the same time use z-index for the overlaying then if I have understood your question correctly it should work

Upvotes: 0

Related Questions