【问题标题】:Force width of flex item to be 50%强制弹性项目的宽度为 50%
【发布时间】:2021-02-28 00:39:40
【问题描述】:

我正在尝试创建一个基于 flex 的容器,其中项目应该在悬停时通过动画展开。所有项目首先应具有相同的宽度,具体取决于容器的总宽度。悬停项目时,悬停的项目应正好是容器总宽度的 50%,其余未悬停的项目将缩小以填充剩余空间。

这似乎是一件很容易做到的事情,但我无法真正理解如何实现我想要的结果。

我试过这个代码:https://codepen.io/tobiasger/pen/xxRWxpV

.flex-container {
  width:100%;
  display:flex;
  height:300px;
}

.flex-item {
  flex:1;
  transition: all 0.4s ease;
}

.flex-item:hover {
  flex-basis:50%;
}

flex-basis 不会导致容器的 50%。我不确定它的百分比是基于什么,它似乎比实际容器宽度更接近窗口宽度。

我还尝试将 50% 的 min-width 值应用于悬停的项目,但这似乎无法制作动画。

目标是不必根据容器包含的项目数为容器创建特定的类。如果可以始终强制悬停的项目恰好是容器宽度的 50%,同时让其余项目平均填充剩余的 50%,并且还可以为这种宽度变化设置动画,我会非常高兴!

【问题讨论】:

  • 你试过 width:50% 吗?

标签: css flexbox


【解决方案1】:

只需将flex-grow:0; 添加到.flex-item:hover

.flex-item:hover {
  flex-basis:50%;
  flex-grow: 0;
}

这也有效

.flex-item:hover {
  flex: 0 50%;
}

【讨论】:

  • 它有点工作,但是元素在瞬间变大,然后动画缩小到50%,所以不幸的是它创造了一种令人讨厌的动画。
  • 你用的是什么浏览器?我在 chrome 中没有遇到这种情况。
  • 尝试flex: 0 50%;flex: 0 0 50%; 而不是单独的 flex-basis 和 flex-grow。这可能行得通。
  • 不幸的是同样的结果。我也在使用 Chrome。
  • 对不起,我在本地代码中的其余项目上有flex-grow:1。将其更改为 flex:1 就像在我的示例中一样,您的解决方案效果很好!很抱歉。
【解决方案2】:

当您按以下方式使用width 而不是flex-basis 时,它会起作用:

html,
body {
  margin: 0;
}

.flex-container {
  width: 100%;
  display: flex;
  height: 300px;
}

.flex-item {
  flex-grow: 1;
  flex-shrink: 1;
  width: calc(100% / 6);
  transition: all 0.4s ease;
}

.flex-item:nth-child(odd) {
  background: #666;
}

.flex-item:nth-child(odd) {
  background: #333;
}

.flex-item:hover {
  width: 50%;
  flex-shrink: 0;
}
<div class="flex-container">
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
  <div class="flex-item"></div>
</div>

【讨论】:

  • 有没有办法防止项目在缩小到最终宽度之前略微增长?如果您按顺序将鼠标悬停在它们上方,您可以看到所有项目在稳定之前都在增长。如果您与我的代码 sn-p 进行比较,则该示例中未悬停的项目在悬停更改之间具有恒定的宽度。
猜你喜欢
  • 2020-12-25
  • 1970-01-01
  • 2018-05-22
  • 2016-07-20
  • 2017-03-16
  • 2017-12-06
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
相关资源
最近更新 更多