首页 > 解决方案 > 动态共享多个元素之间的宽度?

问题描述

我想在css中有一个盒子,它的水平空间由多个元素共享。这些元素应始终使用100% width该元素,除非它们会发生碰撞,在这种情况下,它们会在所有元素之间平均分配可用宽度。

下面的示例显示了在容器中共享空间的 2 个元素。当蓝色移出红色高度时,两者都应拉伸以再次使用 100% 宽度。我在这个例子中使用了 flexbox,以显示width: 100%在项目中使用的意图。但是如果有一个不使用 flexbox 的解决方案,我会很乐意使用它。

html, body {
  background: gray;
}

.col {
  width: 300px;
  height: 150px;
  background: lightgray;
  
  display: flex;
}

.col > div {
  width: 100%;
  height: 50px;
}

.a {
  background: red;
}

.b {
  position: relative;
  background: blue;
  
  top: 0px;
  
  animation: ani 2s infinite;
}

@keyframes ani {
  50% {
    top: 100px;
  }
}
<div class="col">
  <div class="a"></div>
  <div class="b"></div>
</div>

我想知道是否有一个纯 CSS 解决方案。

标签: htmlcssflexbox

解决方案


不确定你需要这个工作的目的是什么,但是如果你有两个 div 并且当第二个 div 达到 50px 时你希望两个 div 都为 100%,那么你也应该为容器使用动画。我在下面创建了简单的代码片段。请让我知道它是否适合您!

html, body {
  background: gray;
}

.col {
  width: 300px;
  height: 150px;
  background: lightgray;
  
  display: flex;
  flex-direction: row;
  animation: anicontainer 2s infinite;
}

.col > div {
  width: 100%;
  height: 50px;
}

.a {
  background: red;
}

.b {
  position: relative;
  background: blue;
  
  top: 0px;
  
  animation: ani 2s infinite;
}

@keyframes ani {
  50% {
    margin-top:-50px;
    top: 100px;
  }
}
@keyframes anicontainer {
  50% {
    flex-direction: column;
  }
}
<div class="col">
  <div class="a"></div>
  <div class="b"></div>
</div>


推荐阅读