css 如何减少Flex中项目之间的间隙

o7jaxewo  于 2023-05-02  发布在  其他
关注(0)|答案(1)|浏览(201)

我试图减少我的图像之间差距扩大时,悬停。
我希望它看起来像这样:expectation
但它目前看起来是这样的:reality
我目前拥有的:

.container {
  display: flex;
  width: 100%;
  box-sizing: border-box;
  padding: 0 15%;
  height: 100vh;
}

.mask {
  flex: 1;
  clip-path: polygon(40% 0, 60% 0, 30% 100%, 10% 100%);
  transition: 0.2s ease-in;
  gap: 2px;
}

.mask>img {
  width: 100%;
  height: calc(100% - 10vh);
  object-fit: cover;
}

.mask:hover {
  flex: 1 2 5%;
  clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
<div class="container">
  <div class="mask">
    <img src="https://picsum.photos/id/22/4434/3729">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/15/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/10/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/3/5000/3333">
  </div>
</div>

我试着使用margin,甚至使用负值,但这似乎不正确。
感谢任何建议,谢谢。

ss2ws0br

ss2ws0br1#

clip-path不会使元素变小,它们仍然在这里,但不可见。因此,要减小差距是元素的实际宽度。
我有两个解决方案,但都不完美。
1.使用clip-path并将.mask的宽度更改为flex-basisflex-grow

.container {
  --gap: 2px;
  display: flex;
  justify-content: center;
  width: 100%;
  box-sizing: border-box;
  padding: 0 15%;
  height: 100vh;
  gap: var(--gap);
}

.mask {
  transition: 0.2s ease-in;
  height: calc(100% - 10vh);
  flex-basis: calc(calc(100% - 3 * var(--gap)) / 4 * 0.6);
  clip-path: polygon(40% 0, 100% 0, 60% 100%, 0 100%);
}

.mask>img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mask:hover {
  flex-grow: 1;
  clip-path: polygon(0 0, 100% 0, 100% 100%, 0 100%);
}
<div class="container">
  <div class="mask">
    <img src="https://picsum.photos/id/22/4434/3729">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/15/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/10/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/3/5000/3333">
  </div>
</div>

1.使用skewX,避免.maskmargin重叠。如果.container的高度会改变。你可能需要js来计算完美的保证金。

.container {
  --gap: 10px;
  display: flex;
  justify-content: center;
  width: 100%;
  box-sizing: border-box;
  padding: 0 15%;
  height: 100vh;
  gap: var(--gap);
}

.mask {
  transition: 0.2s ease-in;
  height: calc(100% - 10vh);
  flex-basis: 50px;
  transform: skewX(-10deg);
}

.mask>img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.mask:hover {
  flex-grow: 1;
  margin: 0 40px;
  transform: skewX(0);
}
<div class="container">
  <div class="mask">
    <img src="https://picsum.photos/id/22/4434/3729">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/15/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/10/2500/1667">
  </div>
  <div class="mask">
    <img src="https://picsum.photos/id/3/5000/3333">
  </div>
</div>

相关问题