我如何使用z-index重叠框?

问题描述 投票:0回答:1

我是html和CSS的新手。我试图了解z-index并希望实现以下输出。我想知道样本是否可行。

Sample image

每次更改所有框的z-index时,总会有一个框无法正确放置。我想我在适当的位置上错过了一些东西。这是我到目前为止的内容

Sample fiddle

.b1,
.b2,
.b3,
.b4,
.b5,
.b6,
.b7 {
  display: flex;
  margin: auto;
  border: 2px solid black;
  height: 200px;
  width: 200px;
  position: absolute;
}

.b1 {
  background: red;
  top: 35%;
  left: 45%;
  z-index: -3;
}
.b2 {
  background: blue;
  top: 30%;
  left: 41em;
  z-index: -3;
}
.b3 {
  background: pink;
  top: 25%;
  right: 40em;
  z-index: -2;
}
.b4 {
  background: cyan;
  top: 4em;
  left: 45%;
  z-index: -3;
}
.b5 {
  background: orange;
  top: 28em;
  right: 37em;
  z-index: 4;
}
.b6 {
  background: green;
  bottom: 7em;
  left: 45%;
  z-index: 5;
}
.b7 {
  background: black;
  top: 51%;
  left: 42em;
  z-index: 6;
}

HTML

    <div class="b1"></div>
    <div class="b2"></div>
    <div class="b3"></div>
    <div class="b4"></div>
    <div class="b5"></div>
    <div class="b6"></div>
    <div class="b7"></div>

This is my output

html css z-index
1个回答
0
投票

您实际上并不需要z-index,但需要一点3D转换技巧即可实现:

body {
 transform-style: preserve-3d;
}

.b1,
.b2,
.b3,
.b4,
.b5,
.b6,
.b7 {
  display: flex;
  margin: auto;
  border: 2px solid black;
  height: 100px;
  width: 100px;
  position: absolute;
}

.b1 {
  background: red;
  top: 30px;
  left: 40%;
  transform:rotateY(1deg);
}
.b2 {
  background: blue;
  top: 80px;
  left: 50%;
}
.b3 {
  background: pink;
  top: 150px;
  right: 40%;
}
.b4 {
  background: cyan;
  top: 80px;
  left: 30%;
}
.b5 {
  background: green;
  top: 200px;
  left: 50%;
}
.b6 {
  background: purple;
  top: 230px;
  left: 40%;
}
.b7 {
  background: black;
  top: 150px;
  left: 28%;
}
<div class="b1"></div>
<div class="b2"></div>
<div class="b3"></div>
<div class="b4"></div>
<div class="b5"></div>
<div class="b6"></div>
<div class="b7"></div>
© www.soinside.com 2019 - 2024. All rights reserved.