You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

实现首尾元素居中的横向滚动图片画廊

实现首尾元素居中的横向滚动图片画廊

嘿,我完全懂你想要的效果——就是让横向画廊的第一张图一开始就稳稳地居中在页面里,滚动到最后一张时也能停在中心位置,而不是顶到容器边缘对吧?这其实不难,咱们只需要给画廊容器加个动态计算的左右内边距,再配合点滚动优化就能搞定,我直接给你改好代码,替换进去就能用~

核心思路

问题的关键是让画廊的首尾有足够的“留白”,刚好等于页面宽度减去图片宽度的一半,这样第一张图初始时会自动居中,滚动到最后一张时,右边的留白也会把它推到中心位置。另外还可以加上滚动吸附效果,让滚动体验更丝滑。

修改后的完整代码

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>profile pics</title>
<style>
body {
  text-align: center;
  font-family: sans-serif;
  display: flex;
  flex-direction: column;
  justify-content: center;
  margin: 0;
  /* 去掉默认的页面内边距,避免影响计算 */
  padding: 0;
}

.gallery {
  display: flex;
  gap: 50px;
  overflow-x: scroll;
  /* 核心:计算左右内边距,让首尾图片居中 */
  padding-left: calc((100vw - 512px) / 2);
  padding-right: calc((100vw - 512px) / 2);
  /* 可选:开启横向滚动吸附,滚动时自动对齐图片中心 */
  scroll-snap-type: x mandatory;
  /* 可选:隐藏滚动条(根据喜好选择) */
  /* scrollbar-width: none; */
}

.profilePic {
  width: 512px;
  height: 512px;
  /* 配合滚动吸附,让每张图滚动到中心时停下 */
  scroll-snap-align: center;
}

.text {
  max-width: 820px;
  margin-left: auto;
  margin-right: auto;
  padding: 0 20px; /* 给文本加左右内边距,避免小屏幕贴边 */
}
</style>
</head>
<body>
<div class="text">
  <h1>my gallery</h1>
  <h3>
    I love to upload images that I find relatable to my Telegram profile, and from time to time I indulge in scrolling through them and find patterns, today I found out that the first one was lost due to the 100 max photos limit (Telegram just did it automatically) so I wanted to create an archive to save them forever and be able to store more than just a hundred of them
  </h3>
</div>
<div class="gallery"></div>
<script>
const cantidadDeFotos = 100;
const gallery = document.querySelector(".gallery")
for (i = cantidadDeFotos; i > 0; i--) {
  let image = document.createElement("img");
  image.src = `img/${i}.PNG`
  image.classList.add("profilePic")
  gallery.appendChild(image);
}
</script>
</body>
</html>

关键修改点说明

  • 动态内边距计算:calc((100vw - 512px) / 2) 这个公式会自动算出页面两侧需要的留白宽度——100vw是当前视口宽度,减去图片的512px宽度,剩下的空间除以2,就是左右各需要的内边距,完美适配不同屏幕大小。
  • Flex布局替代inline-block:原来的inline-block + white-space: nowrap也能实现横向排列,但Flex布局下gap属性能更稳定地控制图片间距,不需要额外处理换行问题。
  • 滚动吸附优化:scroll-snap-type: x mandatory 和 scroll-snap-align: center 搭配,让滚动时每张图片都会自动停在页面中心,体验比普通滚动好很多,你可以根据自己的喜好选择是否保留。

这样修改后,打开页面你就能看到第一张图稳稳居中,滚动到最后一张时也会停在中心位置,完全符合你的需求~

备注:内容来源于stack exchange,提问作者Manuel Latour

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.20 08:43:04