# 仅使用CSS制作轮播

> 在不使用JavaScript或其他库的情况下，如何使用HTML布局和CSS属性制作轮播图，精心制作，实际运用中也未尝不可！

Author: DeathGhost
Published: 2020-04-27 23:56:58
Category: css
Canonical: https://www.deathghost.cn/article/css/72
Keywords: CSS, 轮播图, css轮播图, 焦点图, banner轮播图, 相册轮播图, scroll-snap-align, scroll-snap-type, 滚动, 吸附

上次文章提到关于&ldquo;[CSS Scroll Snapping滚动吸附锁定元素或位置](https://www.deathghost.cn/article/css/40)&rdquo;，今天借此属性在不使用JavaScript或相关库的情况下实现图片轮播效果。

![CSS轮播图](https://www.deathghost.cn/public/upload/article/2020/04/28/1588006676886245.jpg)

仅CSS轮播图

首先通过HTML与CSS实现基础布局设计，设计结构，左侧缩略导航图，右侧展示其完整视觉图片。

这里同样借助上篇文章提到的&ldquo;[CSS Grid 二维网格结构布局](https://www.deathghost.cn/article/css/49)&rdquo;方法。

## HTML结构

侧边栏缩略图，主体部分为视觉主图区域。

<main class="wrap">
  <aside>
    <ul>
      <li>
        <a href="#one">
	  <img src="001.jpg">
	</a>
      </li>
      <li>
       <a href="#two">
	 <img src="002.jpg">
       </a>
      </li>
      <li>
	<a href="#three">
	  <img src="003.jpg">
	</a>
      </li>
      <li>
        <a href="#four">
	  <img src="004.jpg">
	</a>
      </li>
      <li>
	<a href="#five">
	  <img src="005.jpg">
	</a>
      </li>
    </ul>
  </aside>
  <section>
    <img id="one" src="001.jpg">
    <img id="two" src="002.jpg">
    <img id="three" src="003.jpg">
    <img id="four" src="004.jpg">
    <img id="five" src="005.jpg">
  </section>
</main>

## CSS设置

通过CSS Grid布局以及CSS Scroll Snapping属性设置。

.wrap{
	background:rgb(37, 36, 36);
	width:640px;
	height:354px;
	display: grid;
	grid-template-columns: 1fr 5fr;
}
.wrap img{
	width: auto;
	max-width: 100%;
	height: auto;
}
.wrap section{
	height: 100%;
	overflow: auto;
	scroll-snap-type: y mandatory;
}
.wrap section img{
	object-fit: cover;
	height: 100%;
	scroll-snap-align: start;
}
需要注意的是布局grid-template-columns: 1fr 5fr;图片滚动包裹scroll-snap-type: y mandatory;以及图片展示object-fit: cover的设置。

## 效果

您的浏览器不支持 video 标签。

  See the Pen [仅使用CSS制作轮播](https://codepen.io/deathghost/pen/vYNZENJ) by 孙志锋
  ([@deathghost](https://codepen.io/deathghost)) on [CodePen](https://codepen.io).

最后我们可以将其图片滚动变得平滑一点，我们在视觉图区域包裹设置scroll-behavior: smooth即可。

## Related

- Previous: [CSS粘性定位固定表格thead部分元素小方法](https://www.deathghost.cn/article/css/52)
- Next: [CSS container容器查询](https://www.deathghost.cn/article/css/112)
