亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

Home Web Front-end CSS Tutorial Tutorial on using CSS to implement responsive image automatic carousel effect

Tutorial on using CSS to implement responsive image automatic carousel effect

Nov 21, 2023 am 08:37 AM
css Responsive Image Carousel

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/imghw/default1.png"  data-src="image1.jpg"  class="lazy" alt="">
    <img src="/static/imghw/default1.png"  data-src="image2.jpg"  class="lazy" alt="">
    <img src="/static/imghw/default1.png"  data-src="image3.jpg"  class="lazy" alt="">
    <img src="/static/imghw/default1.png"  data-src="image4.jpg"  class="lazy" alt="">
    <img src="/static/imghw/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:

/* 根據(jù)不同屏幕尺寸改變樣式 */
@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 {
  /* 動畫設(shè)置 */
  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");

// 圖片滾動函數(shù)
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 of this Website
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

Hot AI Tools

Undress AI Tool

Undress AI Tool

Undress images for free

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.

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 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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

PHP Tutorial
1488
72
What is the accent-color property? What is the accent-color property? Jul 26, 2025 am 09:25 AM

accent-color is an attribute used in CSS to customize the highlight colors of form elements such as checkboxes, radio buttons and sliders; 1. It directly changes the default color of the selected state of the form control, such as changing the blue check mark of the checkbox to red; 2. Supported elements include input boxes of type="checkbox", type="radio" and type="range"; 3. Using accent-color can avoid complex custom styles and extra DOM structures, and maintain native accessibility; 4. It is generally supported by modern browsers, and old browsers need to be downgraded; 5. Set accent-col

Describe the `vertical-align` property and its typical use cases Describe the `vertical-align` property and its typical use cases Jul 26, 2025 am 07:35 AM

Thevertical-alignpropertyinCSSalignsinlineortable-cellelementsvertically.1.Itadjustselementslikeimagesorforminputswithintextlinesusingvalueslikebaseline,middle,super,andsub.2.Intablecells,itcontrolscontentalignmentwithtop,middle,orbottomvalues,oftenu

How to compile SCSS to CSS? How to compile SCSS to CSS? Jul 27, 2025 am 01:58 AM

InstallDartSassvianpmafterinstallingNode.jsusingnpminstall-gsass.2.CompileSCSStoCSSusingthecommandsassinput.scssoutput.css.3.Usesass--watchinput.scssoutput.csstoauto-compileonsave.4.Watchentirefolderswithsass--watchscss:css.5.Usepartialswith_prefixfo

How to change text color in CSS? How to change text color in CSS? Jul 27, 2025 am 04:25 AM

To change the text color in CSS, you need to use the color attribute; 1. Use the color attribute to set the text foreground color, supporting color names (such as red), hexadecimal codes (such as #ff0000), RGB values (such as rgb(255,0,0)), HSL values (such as hsl(0,100%,50%)), and RGBA or HSLA with transparency (such as rgba(255,0,0,0.5)); 2. You can apply colors to any element containing text, such as h1 to h6 titles, paragraph p, link a (note the color settings of different states of a:link, a:visited, a:hover, a:active), buttons, div, span, etc.; 3. Most

CSS transitions tutorial CSS transitions tutorial Jul 26, 2025 am 09:30 AM

CSStransitionsenablesmoothpropertychangeswithminimalcode,idealforhovereffectsandinteractivefeedback.1.Usethesyntaxtransition:propertydurationtiming-functiondelay;todefinetransitions,liketransition:background-color0.3sease0.1s;.2.Specifytransition-pro

How to purge unused CSS? How to purge unused CSS? Jul 27, 2025 am 02:47 AM

UseautomatedtoolslikePurgeCSSorUnCSStoscanandremoveunusedCSS;2.IntegratepurgingintoyourbuildprocessviaWebpack,Vite,orTailwind’scontentconfiguration;3.AuditCSSusagewithChromeDevToolsCoveragetabbeforepurgingtoavoidremovingneededstyles;4.Safelistdynamic

HTML `style` Tag: Inline vs. Internal CSS HTML `style` Tag: Inline vs. Internal CSS Jul 26, 2025 am 07:23 AM

The style placement method needs to be selected according to the scene. 1. Inline is suitable for temporary modification of single elements or dynamic JS control, such as the button color changes with operation; 2. Internal CSS is suitable for projects with few pages and simple structure, which is convenient for centralized management of styles, such as basic style settings of login pages; 3. Priority is given to reuse, maintenance and performance, and it is better to split external link CSS files for large projects.

css filter property examples css filter property examples Jul 26, 2025 am 08:08 AM

TheCSSfilterpropertyappliesvisualeffectstoelementsdirectlyinCSS,withcommonusesincluding:1.blur()forsofteningimagesorcreatingdepth,2.brightness()toadjustlightnessordarkness,3.contrast()toenhanceorreducevisualdistinction,4.grayscale()forblack-and-white

See all articles