1

When deliberately overlapping (and rotating) adjacent images in CSS/HTML with e.g.

<img src="some_img.png" height= "30%" style="transform:rotate(20deg); z-index: 1"/>
<img src="some_other_img.png" height= "30%" style="transform:rotate(5deg); margin-left:-30px; z-index: 2" />
<img src="yet_another_img.png" height= "30%" style="transform:rotate(-20deg); margin-left:-30px; z-index: 0"/>

How does the image appearance order get decided?

i.e. Is there a way to ensure a specific image in a row of overlapping images remains on top? e.g. the middle one. (see attached examples)

enter image description here

I’ve tried using ‘z-index’ suggested in some related posts (as shown in code above), but I’m not sure if I am using it correctly (I’m relatively new to CSS).

The order seems consistent, but random.

EDIT: question flagged as duplicate of “why does z-index not work?”. Although the answer is the same I believe my question is subtly different. I was not asking specifically why z-index did not work, but how to choose overlap order. The answer is essentially the same, but I believe the question is likely to help people who do not already know to search for “z-index” as the solution. I’ll leave the community to judge whether they agree with me or not and flag for removal if not.

Tristan HB
  • 125
  • 2
  • 8

2 Answers2

1

The z-index property only works on positioned elements. Positioned elements have a position, which is not static (the default). In your case, set the images position to relative.

img {
  position: relative;
}
<img src="http://lorempixel.com/200/100/?1" height= "30%" style="transform:rotate(20deg); z-index: 1"/>
<img src="http://lorempixel.com/200/100/?2" height= "30%" style="transform:rotate(5deg); margin-left:-30px; z-index: 2" />
<img src="http://lorempixel.com/200/100/?3" height= "30%" style="transform:rotate(-20deg); margin-left:-30px; z-index: 0"/>
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
1

In order for z-index property to work the elements need positioning. position: relative works nicely if you dont need to disrupt the normal layout flow.

I have also moved all your styles to separate CSS stylesheet, recommended over inline styles.

img {
  height: 30%;
  width: auto;
  position: relative;
}

.img1 {
  transform:rotate(20deg);
  z-index: 1;
}

.img2 {
  transform:rotate(5deg);
  margin-left:-30px;
  z-index: 2;
}

.img3 {
  transform:rotate(-20deg);
  margin-left:-30px;
  z-index: 0;
}
<img class="img1" src="https://picsum.photos/200" />
<img class="img2" src="https://picsum.photos/220" />
<img class="img3" src="https://picsum.photos/210" />
BugsArePeopleToo
  • 2,976
  • 1
  • 15
  • 16