


It turns out that text carousel and image carousel can also be realized using pure CSS!
Jun 10, 2022 pm 01:00 PMHow to create text carousel and image carousel? The first thing everyone thinks of is whether to use js. In fact, text carousel and image carousel can also be realized using pure CSS. Let’s take a look at the implementation method. I hope it will be helpful to everyone!
Today, I would like to share an animation technique that can be used in actual business. [Recommended learning: css video tutorial]
Skillfully use frame-by-frame animation and tween animation to achieve an infinite loop carousel effect, like this:
Seeing the above diagram, some students can’t help but ask, isn’t this a very simple displacement animation?
Let’s do a simple analysis. On the surface, it seems that only the transform: translate()
of the element is in displacement, But pay attention, there are two difficulties here :
This is an infinite carousel effect. Our animation needs to support infinite carousel switching of any number of elements.
Because it is a carousel Play, so when running to the last one, the animation needs to be cut to the first element
At this point, you can pause and think about it. If there are 20 elements, you need to do something similar. Infinite carousel broadcast, implemented using CSS, how would you do it?
Frame-by-frame animation control overall switching
First of all, I need to use the frame-by-frame animation effect, also known as the step easing function, using In animation-timing-function
, the syntax of steps is as follows:
{ ????/*?Keyword?values?*/ ????animation-timing-function:?step-start; ????animation-timing-function:?step-end; ????/*?Function?values?*/ ????animation-timing-function:?steps(6,?start) ????animation-timing-function:?steps(4,?end); }
If you don’t know much about the syntax of steps
, I strongly recommend that you read my article first Article - An in-depth explanation of CSS animation, which plays a vital role in understanding this article.
Okay, let’s use the example at the beginning of the article. Suppose we have such an HTML structure:
<div class="g-container"> <ul> <li>Lorem ipsum 1111111</li> <li>Lorem ipsum 2222222</li> <li>Lorem ipsum 3333333</li> <li>Lorem ipsum 4444444</li> <li>Lorem ipsum 5555555</li> <li>Lorem ipsum 6666666</li> </ul> </div>
First, we implement such a simple layout:
Here, to achieve the carousel effect and any number, we can use animation-timing-function: steps()
:
:root { // 輪播的個(gè)數(shù) --s: 6; // 單個(gè) li 容器的高度 --h: 36; // 單次動(dòng)畫的時(shí)長 --speed: 1.5s; } .g-container { width: 300px; height: calc(var(--h) * 1px); } ul { display: flex; flex-direction: column; animation: move calc(var(--speed) * var(--s)) steps(var(--s)) infinite; } ul li { width: 100%; } @keyframes move { 0% { transform: translate(0, 0); } 100% { transform: translate(0, calc(var(--s) * var(--h) * -1px)); } }
Don’t panic when you see the above several CSS variables, it’s actually easy to understand:
calc(var(--speed) * var(--s) )
: The time consumption of a single animation* The number of carousels, that is, the total animation durationsteps(var(--s))
It is the number of frames of frame-by-frame animation, here it issteps(6)
, which is easy to understandcalc(var(--s) * var (--h) * -1px))
The height of a single li container * the number of carousels, which is actually the overall height of ul, used to set the end value of frame-by-frame animation
The above effect is actually as follows:
If you add overflow: hidden
to the container, this is the effect :
In this way, we get the overall structure. At least, the entire effect is cyclic.
But since it is only a frame-by-frame animation, you can only see the switching, but there is no transition animation effect between each frame. So, next, we have to introduce tweening animation.
Use tweening animation to achieve switching between two sets of data
We need to use tweening animation to achieve a dynamic switching effect.
This step is actually very simple. What we have to do is to move a set of data from state A to state B using transform
.
If you take one out for demonstration alone, the approximate code is as follows:
<div class="g-container"> <ul style="--s: 6"> <li>Lorem ipsum 1111111</li> <li>Lorem ipsum 2222222</li> <li>Lorem ipsum 3333333</li> <li>Lorem ipsum 4444444</li> <li>Lorem ipsum 5555555</li> <li>Lorem ipsum 6666666</li> </ul> </div>
:root { --h: 36; --speed: 1.2s; } ul li { height: 36px; animation: liMove calc(var(--speed)) infinite; } @keyframes liMove { 0% { transform: translate(0, 0); } 80%, 100% { transform: translate(0, -36px); } }
A very simple animation:
Based on the above effects, if we combine the frame-by-frame animation mentioned at the beginning with the tween animation, the overall movement of ul overlaps with the single movement of li Together:
:root { // 輪播的個(gè)數(shù) --s: 6; // 單個(gè) li 容器的高度 --h: 36; // 單次動(dòng)畫的時(shí)長 --speed: 1.5s; } .g-container { width: 300px; height: calc(var(--h) * 1px); } ul { display: flex; flex-direction: column; animation: move calc(var(--speed) * var(--s)) steps(var(--s)) infinite; } ul li { width: 100%; animation: liMove calc(var(--speed)) infinite; } @keyframes move { 0% { transform: translate(0, 0); } 100% { transform: translate(0, calc(var(--s) * var(--h) * -1px)); } } @keyframes liMove { 0% { transform: translate(0, 0); } 80%, 100% { transform: translate(0, calc(var(--h) * -1px)); } }
can get such an effect:
frame-by-frame animation and tween animation, we have almost achieved a carousel effect.
當(dāng)然,有一點(diǎn)瑕疵,可以看到,最后一組數(shù)據(jù),是從第六組數(shù)據(jù) transform 移動(dòng)向了一組空數(shù)據(jù):
末尾填充頭部第一組數(shù)據(jù)
實(shí)際開發(fā)過輪播的同學(xué)肯定知道,這里,其實(shí)也很好處理,我們只需要在末尾,補(bǔ)一組頭部的第一個(gè)數(shù)據(jù)即可:
改造下我們的 HTML:
<div class="g-container"> <ul> <li>Lorem ipsum 1111111</li> <li>Lorem ipsum 2222222</li> <li>Lorem ipsum 3333333</li> <li>Lorem ipsum 4444444</li> <li>Lorem ipsum 5555555</li> <li>Lorem ipsum 6666666</li> <!--末尾補(bǔ)一個(gè)首條數(shù)據(jù)--> <li>Lorem ipsum 1111111</li> </ul> </div>
這樣,我們再看看效果:
Beautiful!如果你還有所疑惑,我們給容器加上 overflow: hidden
,實(shí)際效果如下,通過額外添加的最后一組數(shù)據(jù),我們的整個(gè)動(dòng)畫剛好完美的銜接上,一個(gè)完美的輪播效果:
完整的代碼,你可以戳這里:CodePen Demo -- Vertical Infinity Loop
https://codepen.io/Chokcoco/pen/RwQVByx
橫向無限輪播
當(dāng)然,實(shí)現(xiàn)了豎直方向的輪播,橫向的效果也是一樣的。
并且,我們可以通過在 HTML 結(jié)構(gòu)中,通過 style 內(nèi)填寫 CSS 變量值,傳入實(shí)際的 li 個(gè)數(shù),以達(dá)到根據(jù)不同 li 個(gè)數(shù)適配不同動(dòng)畫:
<div class="g-container"> <ul style="--s: 6"> <li>Lorem ipsum 1111111</li> <li>Lorem ipsum 2222222</li> <li>Lorem ipsum 3333333</li> <li>Lorem ipsum 4444444</li> <li>Lorem ipsum 5555555</li> <li>Lorem ipsum 6666666</li> <!--末尾補(bǔ)一個(gè)首尾數(shù)據(jù)--> <li>Lorem ipsum 1111111</li> </ul> </div>
整個(gè)動(dòng)畫的 CSS 代碼基本是一致的,我們只需要改變兩個(gè)動(dòng)畫的 transform
值,從豎直位移,改成水平位移即可:
:root { --w: 300; --speed: 1.5s; } .g-container { width: calc(--w * 1px); overflow: hidden; } ul { display: flex; flex-wrap: nowrap; animation: move calc(var(--speed) * var(--s)) steps(var(--s)) infinite; } ul li { flex-shrink: 0; width: 100%; height: 100%; animation: liMove calc(var(--speed)) infinite; } @keyframes move { 0% { transform: translate(0, 0); } 100% { transform: translate(calc(var(--s) * var(--w) * -1px), 0); } } @keyframes liMove { 0% { transform: translate(0, 0); } 80%, 100% { transform: translate(calc(var(--w) * -1px), 0); } }
這樣,我們就輕松的轉(zhuǎn)化為了橫向的效果:
完整的代碼,你可以戳這里:CodePen Demo -- Horizontal Infinity Loop
https://codepen.io/Chokcoco/pen/JjpNBXY
輪播圖?不在話下
OK,上面的只是文字版的輪播,那如果是圖片呢?
沒問題,方法都是一樣的。基于上述的代碼,我們可以輕松地將它修改一下后得到圖片版的輪播效果。
代碼都是一樣的,就不再列出來,直接看看效果:
完整的代碼,你可以戳這里:CodePen Demo -- Horizontal Image Infinity Loop
https://codepen.io/Chokcoco/pen/GRQvqgq
掌握了這個(gè)技巧之后,你可以將它運(yùn)用在非常多只需要簡化版的輪播效果之上。
再簡單總結(jié)一下,非常有意思的技巧:
利用 逐幀動(dòng)畫,實(shí)現(xiàn)整體的輪播的循環(huán)效果
利用 補(bǔ)間動(dòng)畫,實(shí)現(xiàn)具體的 狀態(tài)A 向 狀態(tài)B* 的動(dòng)畫效果
逐幀動(dòng)畫 配合 補(bǔ)間動(dòng)畫 構(gòu)成整體輪播的效果
通過向 HTML 結(jié)構(gòu)末尾補(bǔ)充一組頭部數(shù)據(jù),實(shí)現(xiàn)整體動(dòng)畫的銜接
通過 HTML 元素的 style 標(biāo)簽,利用 CSS 變量,填入實(shí)際的參與循環(huán)的 DOM 個(gè)數(shù),可以實(shí)現(xiàn) JavaScript 與 CSS 的打通
(學(xué)習(xí)視頻分享:web前端)
The above is the detailed content of It turns out that text carousel and image carousel can also be realized using pure CSS!. 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)

Hot Topics

CSS blocks page rendering because browsers view inline and external CSS as key resources by default, especially with imported stylesheets, header large amounts of inline CSS, and unoptimized media query styles. 1. Extract critical CSS and embed it into HTML; 2. Delay loading non-critical CSS through JavaScript; 3. Use media attributes to optimize loading such as print styles; 4. Compress and merge CSS to reduce requests. It is recommended to use tools to extract key CSS, combine rel="preload" asynchronous loading, and use media delayed loading reasonably to avoid excessive splitting and complex script control.

ToimplementdarkmodeinCSSeffectively,useCSSvariablesforthemecolors,detectsystempreferenceswithprefers-color-scheme,addamanualtogglebutton,andhandleimagesandbackgroundsthoughtfully.1.DefineCSSvariablesforlightanddarkthemestomanagecolorsefficiently.2.Us

The topic differencebetweenem, Rem, PX, andViewportunits (VH, VW) LiesintheirreFerencepoint: PXISFixedandbasedonpixelvalues, emissrelative EtothefontsizeFheelementoritsparent, Remisrelelatotherootfontsize, AndVH/VwarebaseDontheviewporttimensions.1.PXoffersprecis

ThebestapproachforCSSdependsontheproject'sspecificneeds.Forlargerprojects,externalCSSisbetterduetomaintainabilityandreusability;forsmallerprojectsorsingle-pageapplications,internalCSSmightbemoresuitable.It'scrucialtobalanceprojectsize,performanceneed

Choosing the correct display value in CSS is crucial because it controls the behavior of elements in the layout. 1.inline: Make elements flow like text, without occupying a single line, and cannot directly set width and height, suitable for elements in text, such as; 2.block: Make elements exclusively occupy one line and occupy all width, can set width and height and inner and outer margins, suitable for structured elements, such as; 3.inline-block: has both block characteristics and inline layout, can set size but still display in the same line, suitable for horizontal layouts that require consistent spacing; 4.flex: Modern layout mode, suitable for containers, easy to achieve alignment and distribution through justify-content, align-items and other attributes, yes

Autoprefixer is a tool that automatically adds vendor prefixes to CSS attributes based on the target browser scope. 1. It solves the problem of manually maintaining prefixes with errors; 2. Work through the PostCSS plug-in form, parse CSS, analyze attributes that need to be prefixed, and generate code according to configuration; 3. The usage steps include installing plug-ins, setting browserslist, and enabling them in the build process; 4. Notes include not manually adding prefixes, keeping configuration updates, prefixes not all attributes, and it is recommended to use them with the preprocessor.

AnimatingSVGwithCSSispossibleusingkeyframesforbasicanimationsandtransitionsforinteractiveeffects.1.Use@keyframestodefineanimationstagesforpropertieslikescale,opacity,andcolor.2.ApplytheanimationtoSVGelementssuchas,,orviaCSSclasses.3.Forhoverorstate-b

Theconic-gradient()functioninCSScreatescirculargradientsthatrotatecolorstopsaroundacentralpoint.1.Itisidealforpiecharts,progressindicators,colorwheels,anddecorativebackgrounds.2.Itworksbydefiningcolorstopsatspecificangles,optionallystartingfromadefin
