Matt
Matt

Reputation: 1923

Put 2 images on top of each other

I'm currently making a Cluedo-esque style of website where people can suspect people or declare them innocent. When I person is innocent, I want to put a red cross over their pictures.

But currently I'm struggling to position everything. I've managed to put 2 images over each other, but not on the correct position.

Current situation: A table with pictures in the first row. This is the CSS added to the pictures:

<td><img src="bottom.jpg" style="z-index: 0; position: absolute"  />
    <img src="top.png"    style="z-index: 1; position: absolute"/>
</td>

Current situation

How can I the position of both of my images? Removing the "position: absolute" doesn't work, so how can I fix this and still keep both of the pictures in the table cell.

The solution should work for all the pictures in the table (a general CSS class for each of the pictures (top/bottom).

Thanks!

EDIT after Fabio's suggestion

It solved a part of the issue, but not entirely. This is the current situation with the exact code you suggested:

New situation

Upvotes: 4

Views: 37262

Answers (2)

Hashem Qolami
Hashem Qolami

Reputation: 99554

You should wrap the images by an additional <div> in order to use relative positioning. Because the effect of position: relative; on table-cell elements is undefined.

9.3.1 Choosing a positioning scheme: 'position' property

The effect of position:relative on table-row-group, table-header-group, table-footer-group, table-row, table-column-group, table-column, table-cell, and table-caption elements is undefined.

EXAMPLE HERE

<td>
  <div class="img-container">
    <img class="top" src="http://lorempixel.com/200/150" alt="">
    <img class="bottom" src="http://placehold.it/200x150/fe0" alt="">
  </div>
</td>

Then you could simply remove the .top image from document normal flow an place that over the other one as follows:

CSS

.img-container { position: relative; }

.img-container .top {
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
}

PS: I've added a transition of opacity property in the online demo to hide .top images on mouse over.

Upvotes: 17

Devin
Devin

Reputation: 7720

First of all remove your inline styles. If possible give classes to images, like this:

<td><img  class="bottomimg" src="bottom.jpg"  />
    <img  class="topimg" src="top.png" />
</td>

then in CSS

td{position:relative; z-index:0}
.bottomimg{position:absolute; top:0; left:0; z-index:1}
.topimg{position:absolute; top:0; left:0; z-index:2}

Upvotes: 0

Related Questions