用溢出隐藏 div

时间:2020-12-24 23:46:41

标签: css css-position overflow

我希望蓝色方块可见,而红色方块隐藏在蓝色方块下方。蓝色和红色不应重叠,它们需要一个接一个地排列。但是我的 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>

2 个答案:

答案 0 :(得分:1)

我的理解是你需要将红色方块隐藏在蓝色方块下面,这样你就可以使用 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>

答案 1 :(得分:0)

我将 #red top 属性更新为 100%。如下图:

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