


Tutorial on using CSS to implement responsive image automatic carousel effect
Nov 21, 2023 am 08:37 AMWith 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
- 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.
- 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%; /* 將子容器寬度擴(kuò)大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.
- 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.
- 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 { /* 動(dòng)畫(huà)設(shè)置 */ animation: carousel-animation 10s infinite linear; } .carousel-items:hover { /* 鼠標(biāo)懸停時(shí)終止動(dòng)畫(huà) */ 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.
- 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"); // 圖片滾動(dòng)函數(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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

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
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

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

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

Astackingcontextisaself-containedlayerinCSSthatcontrolsthez-orderofoverlappingelements,wherenestedcontextsrestrictz-indexinteractions;itiscreatedbypropertieslikez-indexonpositionedelements,opacity

In web development, the choice of CSS units depends on design requirements and responsive performance. 1. Pixels (px) are used to fix sizes such as borders and icons, but are not conducive to responsive design; 2. Percentage (%) is adjusted according to the parent container, suitable for streaming layout but attention to context dependence; 3.em is based on the current font size, rem is based on the root element font, suitable for elastic fonts and unified theme control; 4. Viewport units (vw/vh/vmin/vmax) are adjusted according to the screen size, suitable for full-screen elements and dynamic UI; 5. Auto, inherit, initial and other values are used to automatically calculate, inherit or reset styles, which helps to flexibly layout and style management. The rational use of these units can improve page flexibility and responsiveness.

Backdrop-filter is used to apply visual effects to the content behind the elements. 1. Use backdrop-filter:blur(10px) and other syntax to achieve the frosted glass effect; 2. Supports multiple filter functions such as blur, brightness, contrast, etc. and can be superimposed; 3. It is often used in glass card design, and it is necessary to ensure that the elements overlap with the background; 4. Modern browsers have good support, and @supports can be used to provide downgrade solutions; 5. Avoid excessive blur values and frequent redrawing to optimize performance. This attribute only takes effect when there is content behind the elements.

The style of the link should distinguish different states through pseudo-classes. 1. Use a:link to set the unreached link style, 2. a:visited to set the accessed link, 3. a:hover to set the hover effect, 4. a:active to set the click-time style, 5. a:focus ensures keyboard accessibility, always follow the LVHA order to avoid style conflicts. You can improve usability and accessibility by adding padding, cursor:pointer and retaining or customizing focus outlines. You can also use border-bottom or animation underscore to ensure that the link has a good user experience and accessibility in all states.

Use text-align:center to achieve horizontal centering of text; 2. Use Flexbox's align-items:center and justify-content:center to achieve vertical and horizontal centering; 3. Single-line text can be vertically centered by setting line-height equal to the container height; 4. Absolute positioning elements can be combined with top: 50%, left: 50% and transform:translate (-50%, -50%) to achieve centering; 5. CSSGrid's place-items:center can also achieve dual-axis centering at the same time. It is recommended to use Flexbox or Grid first in modern layouts.

User agent stylesheets are the default CSS styles that browsers automatically apply to ensure that HTML elements that have not added custom styles are still basic readable. They affect the initial appearance of the page, but there are differences between browsers, which may lead to inconsistent display. Developers often solve this problem by resetting or standardizing styles. Use the Developer Tools' Compute or Style panel to view the default styles. Common coverage operations include clearing inner and outer margins, modifying link underscores, adjusting title sizes and unifying button styles. Understanding user agent styles can help improve cross-browser consistency and enable precise layout control.
