search
HomeWeb Front-endCSS TutorialTutorial on using CSS to implement responsive image automatic carousel effect

Tutorial on using CSS to implement responsive image automatic carousel effect

With the popularity of mobile devices, web design needs to take into account factors such as device resolution and screen size of different terminals to achieve a good user experience. When implementing responsive design of a website, it is often necessary to use the image carousel effect to display the content of multiple images in a limited visual window, and at the same time, it can also enhance the visual effect of the website. This article will introduce how to use CSS to achieve a responsive image automatic carousel effect, and provide code examples and analysis.

Implementation ideas

The implementation of responsive image carousel can be achieved through CSS flex layout. In a fixed container, set up a flex container to contain each image in a flex sub-container. Then by setting the arrangement of the flex sub-containers and the width of the sub-elements, the tiled arrangement of the pictures is achieved. However, because the width of the container will be different under different screen sizes, you need to use media queries to dynamically change the width of the container and sub-elements to adapt to different screen resolutions. Then by setting the animation effect of CSS3, the automatic carousel effect is realized, and the sliding effect is realized through js.

Implementation steps

  1. HTML part

First, we need to create a container containing multiple images in the HTML part, as shown below:

<div class="carousel-container">
  <div class="carousel-items">
    <img src="/static/imghwm/default1.png"  data-src="image1.jpg"  class="lazy" alt="">
    <img src="/static/imghwm/default1.png"  data-src="image2.jpg"  class="lazy" alt="">
    <img src="/static/imghwm/default1.png"  data-src="image3.jpg"  class="lazy" alt="">
    <img src="/static/imghwm/default1.png"  data-src="image4.jpg"  class="lazy" alt="">
    <img src="/static/imghwm/default1.png"  data-src="image5.jpg"  class="lazy" alt="">
  </div>
  <div class="carousel-prev"></div>
  <div class="carousel-next"></div>
</div>

Among them, .carousel-container is the container style name, .carousel-items is the sub-container style name contained in the image, .carousel-prev and .carousel-next are the left and right arrow style names, we will use it in the CSS section Set style.

  1. CSS part

Next, we need to set the style in the CSS part, including the style of the container, sub-container and arrow. The specific code is as follows:

.carousel-container {
  position: relative;
  overflow: hidden;
  width: 100%;
  height: auto;
}

.carousel-items {
  display: flex;
  flex-wrap: nowrap;
  width: 500%; /* 将子容器宽度扩大5倍 */
}

.carousel-items img {
  width: 20%;
  margin-right: 1rem;
  flex: 1;
}

.carousel-prev,
.carousel-next {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 50px;
  height: 50px;
  background-color: rgba(0,0,0,0.5);
  color: #fff;
  text-align: center;
  line-height: 50px;
  cursor: pointer;
}

.carousel-prev {
  left: 0;
}

.carousel-next {
  right: 0;
}

In the style definition, we set relative positioning for the container to achieve absolute positioning of subcontainers and arrows. Using overflow:hidden, you can hide the overflowing parts of sub-containers in the container. The sub-container adopts flex layout, and the nowrap attribute prevents the sub-container elements from wrapping. And set the width of the subcontainer to 500%. By setting the width of the pictures in the subcontainer to 20%, each row can display 5 pictures, and set the margin-right between pictures to 1rem to make the display effect more beautiful. The left and right arrows are centered vertically via absolute positioning and negative margin-top.

  1. Media query setting responsive attributes

Under different screen sizes, the width of the container and sub-elements need to be dynamically changed to adapt to different screen resolutions. We can set responsive properties through media queries and change the width of the container and sub-containers under different screen sizes, as shown below:

/* 根据不同屏幕尺寸改变样式 */
@media (max-width: 768px) {
  .carousel-items img {
    width: 50%;
  }
  .carousel-container {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .carousel-items img {
    width: 100%;
    margin-right: 0;
  }
  .carousel-container {
    height: 180px;
  }
}

In the above example, we set the carousel based on the window size change- items img and carousel-container styles. On a small screen, we set each image to 50% width, do not set margin-right between images, and set the height to 250px in the .crosso container; on a smaller screen, we set the image to 100% The width is set to 180px in the .crosso container.

  1. CSS3 animation

Using CSS3 animation, you can achieve the automatic carousel effect of images. The code example is as follows:

@keyframes carousel-animation {
  0% {
      transform: translateX(0);
  }
  100% {
      transform: translateX(-100%);
  }
}

.carousel-items {
  /* 动画设置 */
  animation: carousel-animation 10s infinite linear;
}

.carousel-items:hover {
  /* 鼠标悬停时终止动画 */
  animation-play-state: paused;
}

In the above example, we The picture subcontainer is set to scroll once every 10 seconds. The animation is completed by carousel-animation. Linear means the animation is linear, and infinite means the animation loops infinitely.

  1. JavaScript to achieve the sliding effect

Finally, we use JavaScript to achieve the image sliding effect when the left and right arrows are clicked. The code example is as follows:

// 获取左右箭头元素
var prev = document.querySelector(".carousel-prev");
var next = document.querySelector(".carousel-next");

// 图片滚动函数
function carouselScroll(direction) {
  var container = document.querySelector(".carousel-items");
  var minScrollLeft = 0;
  var maxScrollLeft = container.scrollWidth - container.clientWidth;
  var increment = 20 * direction;

  container.scrollLeft += increment;

  if (container.scrollLeft < minScrollLeft) {
    container.scrollLeft = maxScrollLeft;
  } else if (container.scrollLeft > maxScrollLeft) {
    container.scrollLeft = minScrollLeft;
  }
};

// 给左右箭头绑定事件
prev.addEventListener("click", function() {
  carouselScroll(-1);
});

next.addEventListener("click", function() {
  carouselScroll(1);
});

In the above example, we obtain the left and right arrow elements through querySelector and bind the click event. Use the carouselScroll function to achieve the picture sliding effect every time you click. container.scrollWidth represents the effective width of the sub-container, and container.clientWidth represents the visible width. When scrolling to the edge of the container, the scroll position will be set to the opposite position to achieve the effect of circular scrolling.

Summary

In this article, we used CSS3’s flex layout and animation effects, as well as JavaScript to implement the click events of the left and right arrows, and successfully implemented the responsive image automatic carousel effect. We also achieved a richer responsive design by adding media queries and hover effects. The code examples have a certain degree of generality and are also useful as a reference for beginners.

The above is the detailed content of Tutorial on using CSS to implement responsive image automatic carousel effect. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

@keyframes CSS: The most used tricks@keyframes CSS: The most used tricksMay 08, 2025 am 12:13 AM

@keyframesispopularduetoitsversatilityandpowerincreatingsmoothCSSanimations.Keytricksinclude:1)Definingsmoothtransitionsbetweenstates,2)Animatingmultiplepropertiessimultaneously,3)Usingvendorprefixesforbrowsercompatibility,4)CombiningwithJavaScriptfo

CSS Counters: A Comprehensive Guide to Automatic NumberingCSS Counters: A Comprehensive Guide to Automatic NumberingMay 07, 2025 pm 03:45 PM

CSSCountersareusedtomanageautomaticnumberinginwebdesigns.1)Theycanbeusedfortablesofcontents,listitems,andcustomnumbering.2)Advancedusesincludenestednumberingsystems.3)Challengesincludebrowsercompatibilityandperformanceissues.4)Creativeusesinvolvecust

Modern Scroll Shadows Using Scroll-Driven AnimationsModern Scroll Shadows Using Scroll-Driven AnimationsMay 07, 2025 am 10:34 AM

Using scroll shadows, especially for mobile devices, is a subtle bit of UX that Chris has covered before. Geoff covered a newer approach that uses the animation-timeline property. Here’s yet another way.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools