【问题标题】:Expanding div's width to shrink anothers扩大 div 的宽度以缩小另一个
【发布时间】:2020-01-02 18:20:53
【问题描述】:

我正在尝试扩大 div 的宽度,这样做时我还希望其宽度左侧的 div 缩小到宽度 0px 并消失。

这就是我的got to

我无法缩小第一个(左)div 的宽度。我还需要第三个 div(右)永远不会改变大小,不受动画的影响。

html

 <div id='container'>
      <div id='one'>one</div>
      <div id='two'>two</div>
      <div id='three'>three</div>
 </div>

css

#container {
  position: relative;
  border-style: dotted;
  height: 100px;
  width: 318px;
}

#one {
  border-style: dotted;
  border-color: red;
  left: 0;
  width: 200px;
  height: 100px;
  min-width: 0px;
  position: absolute;
}

#two {
  border-style: dotted;
  border-color: cadetblue;
  width: 0px;
  height: 100px;
  max-width: 200px;
  position: absolute;
  top: 0;
  right: 100px;
  animation: enter-right 20s linear infinite;
}
#three {
  border-style: dotted;
  border-color: goldenrod;
  width: 100px;
  right: 0;
  min-width: 100px;
  height: 100px;
  position: absolute;
}

@keyframes enter-right {
  0% {
    transform: translateX(0);
  }
  10%,
  90% {
    transform: translateX(0);
  }
  98%,
  100% {
    width: 100%;

  }
}

【问题讨论】:

  • 你的盒子有absolute的位置有什么特别的原因吗?

标签: javascript html css reactjs css-animations


【解决方案1】:

我在容器上使用了 display: flex 并从元素中删除了所有定位。我认为它可以满足您的要求:

.App {
  font-family: sans-serif;
  text-align: center;
}

#container {
  display: flex;
  border-style: dotted;
  height: 100px;
  width: 318px;
}

#one {
  border-style: dotted;
  border-color: red;
  width: 200px;
  height: 100px;
  min-width: 0px;
}

#two {
  border-style: dotted;
  border-color: cadetblue;
  width: 0px;
  height: 100px;
  max-width: 200px;
  animation: enter-right 20s linear infinite;
}

#three {
  border-style: dotted;
  border-color: goldenrod;
  width: 100px;
  min-width: 100px;
  height: 100px;
}

@keyframes enter-right {
  0% {
    transform: translateX(0);
  }
  10%,
  90% {
    transform: translateX(0);
  }
  98%,
  100% {
    width: 100%;
    /* transform: translateX(100%); */
  }
}

【讨论】:

    【解决方案2】:

    如果没有理由使用绝对位置,您可以尝试使用内联 Flexbox 容器,在第二个元素的 flex 速记属性上使用动画

    main {
      display: inline-flex; }
    
    main div {
      margin: 0 5px;
      box-sizing: border-box;
      overflow: hidden;
      border: 3px dashed #9bc;}
    
    #one { 
      flex-basis: 200px; 
      width: 200px; }
    
    #two { 
      flex: 1 0 0;
      animation: expand 5s linear 0s forwards; }
    
    #three { 
      flex: 0 0 100px;
      width: 100px; }
    
    @keyframes expand {
      100% { flex: 1 0 200px; }
    }
    <main>
      <div id="one">one</div>
      <div id="two">two</div>
      <div id="three">three</div>
    </main>  

    【讨论】:

      猜你喜欢
      • 2016-04-06
      • 2023-04-03
      • 2016-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 2011-09-03
      相关资源
      最近更新 更多