Подтвердить что ты не робот

Цветочный парадокс CSS z-index

Я хотел бы создать парадоксальный эффект с помощью свойства z-index CSS.

В моем коде у меня есть пять кругов, как на изображении ниже, и все они абсолютно расположены без определенного z-index. Поэтому по умолчанию каждый круг перекрывает предыдущий.

Прямо сейчас, круг 5 перекрывает круг 1 (левое изображение). Парадокс, который я хотел бы достичь, состоит в том, чтобы в то же время окружить 1 под кружком 2 и над кругом 5 (как в правильном изображении).

http://paradox.schramek.cz/1.jpg

Здесь мой код

Разметка:

<div class="item i1">1</div>
<div class="item i2">2</div>
<div class="item i3">3</div>
<div class="item i4">4</div> 
<div class="item i5">5</div>

CSS

.item {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px solid red;
    background: silver;
    border-radius: 50%;
    text-align: center;
}

.i1 { position: absolute; top: 30px; left: 0px; }
.i2 { position: absolute; top: 0px; left: 35px; }
.i3 { position: absolute; top: 30px; left: 65px; }
.i4 { position: absolute; top: 70px; left: 50px; }
.i5 { position: absolute; top: 70px; left: 15px; }

Живой пример также доступен в http://jsfiddle.net/Kx2k5/.

Я пробовал много методов со штабелями, стекированием и т.д. Я прочитал некоторые статьи об этих методах, но не успел. Как я могу это решить?

4b9b3361

Ответ 1

Здесь моя попытка: http://jsfiddle.net/Kx2k5/1/
(успешно протестировано на Fx27, Ch33, IE9, Sf5.1.10 и Op19)


CSS

.item {
   /* include borders on width and height */  
   -webkit-box-sizing : border-box;
   -moz-box-sizing    : border-box;
   box-sizing         : border-box;
   ...
}

.i1:after {
   content: "";

   /* overlap a circle over circle #1 */
   position : absolute;
   z-index  : 1;
   top      : 0;
   left     : 0;
   height   : 100%;
   width    : 100%;

   /* inherit border, background and border-radius */
   background    : inherit;
   border-bottom : inherit;
   border-radius : inherit;

   /* only show the bottom area of the pseudoelement */
   clip          : rect(35px 50px 50px 0);
}

В основном я перекрыл псевдоэлемент :after по первому кругу (с некоторыми унаследованными свойствами), тогда я обрезал его с помощью свойства clip(), поэтому я вижу только его нижнюю часть (где circle #1 перекрывает круг #5).

Для свойств CSS, которые я использовал здесь, этот пример должен работать даже на IE8 (box-sizing, clip(), inherit), и там поддерживаются псевдоэлементы)


Снимок экрана результирующего эффекта

enter image description here

Ответ 2

Моя попытка также использовать clip. Идея заключалась в том, чтобы иметь половину и половину для div. Таким образом, настройка z-index будет работать.

Итак, вы можете установить верхнюю часть на z-index: -1, а нижнюю - на z-index: 1.

Результат:

enter image description here

.item {
  width: 50px;
  height: 50px;
  line-height: 50px;
  border: 1px solid red;
  background: silver;
  border-radius: 50%;
  text-align: center;
}
.under {
  z-index: -1;
}
.above {
  z-index: 1;
  overflow: hidden;
  clip: rect(30px 50px 60px 0);
}
.i1 {
  position: absolute;
  top: 30px;
  left: 0px;
}
.i2 {
  position: absolute;
  top: 0px;
  left: 35px;
}
.i3 {
  position: absolute;
  top: 30px;
  left: 65px;
}
.i4 {
  position: absolute;
  top: 70px;
  left: 50px;
}
.i5 {
  position: absolute;
  top: 70px;
  left: 15px;
}
<div class="item i1 under">1</div>
<div class="item i1 above">1</div>
<div class="item i2">2</div>
<div class="item i3">3</div>
<div class="item i4">4</div>
<div class="item i5">5</div>

Ответ 3

Вот иди сюда.

Я также использую псевдоэлемент, расположенный поверх первого круга, но вместо того, чтобы использовать клип, я сохраняю его прозрачный фон и просто придаю ему вставку-тень, соответствующую цвету фона кругов (серебро) в качестве красной границы, чтобы покрыть нижние правые стороны границы круга.

Демо

CSS (отличается от начальной)

.i1 { 
  position: absolute; top: 30px; left: 0px;
  &:before {
    content: '';
    position: absolute;
    z-index: 100;
    top: 0;
    left: 0;
    width: 50px;
    height: 50px;
    border-radius:  50%;
    box-shadow: inset 5px -5px 0 6px silver;
    border-bottom: solid 1px red;
  }
}

Конечный продукт enter image description here

Ответ 4

К сожалению, следующее является теоретическим ответом, так как по какой-то причине я не могу заставить -webkit-transform-style: preserve-3d; работать (приходится делать какую-то очевидную ошибку, но, похоже, не может понять это). В любом случае, прочитав свой вопрос, я, как и каждый парадокс, задавался вопросом, почему это только кажущаяся невозможность, а не реальная. Еще несколько секунд я понимаю, что в реальной жизни листья немного повернуты, что позволяет такой вещи существовать. Итак, я хотел придумать простую демонстрацию техники, но без предыдущего свойства, которое невозможно (оно обращается к плоскому родительскому слою). В любом случае, вот базовый код, тем не менее

<div class="container">
    <div>
        <div class="i1 leaf">
            <div class="item">1</div>
        </div>
        <div class="i2 leaf">
            <div class="item">2</div>
        </div>
        <div class="i3 leaf">
            <div class="item">3</div>
        </div>
        <div class="i4 leaf">
            <div class="item">4</div>
        </div>
        <div class="i5 leaf">
            <div class="item">5</div>
        </div>
    </div>
</div>

И css:

.i1 {
    -webkit-transform:rotateZ(288deg)
}
.i2 {
    -webkit-transform:rotateZ(0deg)
}
.i3 {
    -webkit-transform:rotateZ(72deg)
}
.i4 {
    -webkit-transform:rotateZ(144deg)
}
.i5 {
    -webkit-transform:rotateZ(216deg)
}
.leaf { 
    position:absolute;
    left:35px;
    top:35px;
}
.leaf > .item {
    -webkit-transform:rotateY(30deg) translateY(35px)
}

И вы можете найти полный полный код здесь.

Ответ 5

JS Fiddle

HTML

<div class="item i1">1</div>
<div class="item i2">2</div>
<div class="item i3">3</div>
<div class="item i4">4</div>
<div id="five">5</div>
<div class="item2 i5"></div>
<div class="item3 i6"></div>

CSS

.item {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px solid red;
    background: silver;
    border-radius: 50%;
    text-align: center;
}
.item2 {
      width: 25px;
    height: 50px;
    line-height: 50px;
    border: 1px solid red;
    border-right: none;
    border-radius: 50px 0 0 50px;
    background: silver 50%;
    background-size: 25px;
    text-align: center;   
        z-index: -3;
}
.item3 {
    width: 25px;
    height: 50px;
    line-height: 50px;
    border: 1px solid red;
    border-left: none;
    border-radius: 0 50px 50px 0;
    background: silver 50%;
    background-size: 25px;
    text-align: center;    
}
.i1 {
    position: absolute;
    top: 30px;
    left: 0px;
}
.i2 {
    position: absolute;
    top: 0px;
    left: 35px;
}
.i3 {
    position: absolute;
    top: 30px;
    left: 65px;
}
.i4 {
    position: absolute;
    top: 70px;
    left: 55px;
}
.i5 {
    position: absolute;
    top: 70px;
    left: 15px;
}
.i5 {
    position: absolute;
    top: 72px;
    left:19px;

}
.i6 {
    position: absolute;
    top: 72px;
    left: 44px;
}
#five {
     position: absolute;
    top: 88px;
    left: 40px;
    z-index: 100;
}

Ответ 6

JS Fiddle LIVE DEMO

Работает и с IE8.

HTML

<div class="half under"><div class="item i1">1</div></div>
<div class="half above"><div class="item i1">1</div></div>
<div class="item i2">2</div>
<div class="item i3">3</div>
<div class="item i4">4</div> 
<div class="item i5">5</div>

CSS

.item {
    width: 50px;
    height: 50px;
    line-height: 50px;
    border: 1px solid red;
    background: silver;
    border-radius: 50%;
    text-align: center;
}
.half {
    position: absolute;
    overflow: hidden;
    width: 52px;
    height: 26px;
    line-height: 52px;
    text-align: center;
}
.half.under {
    top: 30px; 
    left: 0px;
    z-index: -1;
    border-radius: 90px 90px 0 0;
}
.half.above {
    top: 55px;
    left: 0px;
    z-index: 1;
    border-radius: 0 0 90px 90px;
}
.half.above .i1 { margin-top:-50%; }
.i2 { position: absolute; top: 0px; left: 35px;}
.i3 { position: absolute; top: 30px; left: 65px;}
.i4 { position: absolute; top: 70px; left: 50px; }
.i5 { position: absolute; top: 70px; left: 15px; }