首页 > 解决方案 > 隐藏 div 溢出

问题描述

我希望蓝色方块可见,红色方块隐藏在蓝色方块下方。蓝色和红色不应该重叠,它们需要一个接一个地排序。但我的 CSS 没有这样做。我错过了什么?

document.getElementById('startAnim').addEventListener('click', function() {
  document.getElementById('red').classList.add('animate');
});
#background {
  position: relative;
  background-color: #3CF;
  width: 50px;
  height: 50px;
  overflow-y: hidden;
  border: medium;
}

#blue {
  background-color: blue;
  width: 50px;
  height: 50px;
  border: thin;
  top: 0%;
  border-color: #000;
  border-width: 1px;
}

#red {
  background-color: red;
  width: 50px;
  height: 50px;
  top: 50%;
  border: thin;
  border-color: #000;
  border-width: 1px;
}

.sq {
  position: absolute;
}

.animate {
  -webkit-animation-name: slidediv;
  /* Chrome, Safari, Opera */
  -webkit-animation-duration: 4s;
  /* Chrome, Safari, Opera */
  -webkit-animation-timing-function: ease-in-out;
}


/* Standard syntax */

@keyframes slidediv {
  0% {
    top: 10px;
  }
  100% {
    top: 100px;
  }
}
<div id="background">
  <div id="blue" class='sq'></div>
  <div id="red" class='sq'></div>
</div>
<button id="startAnim"> Start </button>

标签: csscss-positionoverflow

解决方案


我的理解是,您需要将红色方块隐藏在蓝色方块下方,因此您可以使用 z-index 来解决此问题,如果您正在寻找,请尝试我的片段

document.getElementById('startAnim').addEventListener('click', function() {
  document.getElementById('blue').classList.add('animate');
});
#background {
  position: relative;
  background-color: #3CF;
  width: 50px;
  height: 50px;
  overflow-y: hidden;
  border: medium;
}

#blue {
  background-color: blue;
  width: 50px;
  height: 50px;
  border: thin;
  top: 0%;
  border-color: #000;
  border-width: 1px;
  z-index:7;
}

#red {
  background-color: red;
  width: 50px;
  height: 50px;
  top: 0%;
  border: thin;
  border-color: #000;
  border-width: 1px;
  z-index:6;
}

.sq {
  position: absolute;
}

.animate {
  -webkit-animation-name: slidediv;
  /* Chrome, Safari, Opera */
  -webkit-animation-duration: 4s;
  /* Chrome, Safari, Opera */
  -webkit-animation-timing-function: ease-in-out;
}


/* Standard syntax */

@keyframes slidediv {
  0% {
    top: 0px;
  }
  100% {
    top: 100px;
  }
}
<div id="background">
  <div id="blue" class='sq'></div>
  <div id="red" class='sq'></div>
</div>
<button id="startAnim"> Start </button>


推荐阅读