首页 > 解决方案 > 使用背景图像转换的极简图像滑块,包含最少的 HTML 和 CSS

问题描述

在尝试使用尽可能少的代码 HTML 代码(并尽可能多地放入 CSS)设置背景时,我被困在这个jsfiddle演示中。

主要问题
为什么第三张和第四张幻灯片的背景大小中心原点与第一张和第二张幻灯片不同?尽管在 CSS 中明确设置了这些规则,但删除该-image部分并仅使用速记显然会破坏背景位置和居中。background我忽略了什么?

奖金问题
过渡有两个效果:首先是水平滑动效果,然后是最后的放大。是否有可能使两种效果并行而不是一个接一个地工作?换句话说,在幻灯片水平滑动时开始缩放,以获得更动态的平滑过渡?

.

style="background-image: url(https://...
给出所需的缩放/居中结果,背景图像很好地拟合/居中:
在此处输入图像描述

.

style="background: url(https://...
给出不希望的结果,背景图像不正确拟合/居中:
在此处输入图像描述

标签: htmlcssflexboxbackgroundbackground-image

解决方案


CSS变量是为此目的而制作的,您可以调整背景大小以获得需要的过渡效果:

container {
  display: flex;
  margin: auto;
  width: 612px;
  outline: 1px solid black;
  height: 306px;
}

slide {
  flex: 1;
  background-image: var(--i);
  background-position: center;
  background-size: auto 100%;
  padding: 2px 0 0 2px;
  color: rgba(0, 0, 0, 0.5);
  transition: all .67s ease;
}

container slide:hover {
  flex: 15;
  background-size: auto 120%;
}
<container>
  <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/4185141/galshir-cactus-coffee.png)">1</slide>
  <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/6146136/galshir-tea-biscuit_2x.png)">2</slide>
  <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/4185141/galshir-cactus-coffee.png)">3</slide>
  <slide style="--i: url(https://cdn.dribbble.com/users/729829/screenshots/6146136/galshir-tea-biscuit_2x.png)">4</slide>
</container>


推荐阅读