Home > Article > Web Front-end > How to achieve scrolling effect in css
CSS to achieve scrolling effect
Scrolling effect is usually used for various interactions, animations and navigation in website page design. Most conventional website scrolling effects can be achieved through HTML CSS. This article will briefly introduce several of them.
The overflow attribute of HTML tags wrapping content (such as div) is scroll, and then use the position attribute to determine the position of the content area to achieve scrolling Effect. The code is as follows:
<div style="width:400px; height:200px; overflow:scroll; position:relative"> <div style="width:600px; height:600px; position:absolute; top:0; left:0"> <!-- 内容区域 --> <!-- 内容部分 --> </div> </div>
Using the translateY or translateX of the transform attribute can achieve the scrolling effect and scroll the content through displacement. The code is as follows:
.container{ width:400px; height:200px; overflow:hidden; } .content{ width:600px; height:600px; transform: translateY(0); transition: transform 0.2s ease-out; }
The JS code part is as follows:
let content = document.querySelector('.content'); let offsetY = 0; //内容向上偏移的距离 setInterval(() => { content.style.transform = `translateY(-${offsetY}px)`; offsetY += 1; }, 50);
CSS animation can make the scrolling effect a simple and smooth interaction Effect. The code is as follows:
.container{ width:400px; height:200px; overflow:hidden; } .content{ width:600px; height:600px; animation: scroll 5s linear infinite; } @keyframes scroll { 0% { transform: translateY(0); } 100% { transform: translateY(-400px); } }
By listening to the wheel event and modifying the scrollTop or scrollLeft value of the element, you can achieve a manual scrolling effect. The code is as follows:
<div style="width:400px; height:200px; overflow:scroll"> <div style="width:600px; height:600px"> <!-- 内容区域 --> <!-- 内容部分 --> </div> </div>
The JS code part is as follows:
let content = document.querySelector('.content'); let step = 100; //每次滚动的距离 document.querySelector('.container').addEventListener('wheel', function(event){ event.preventDefault(); content.scrollTop += event.deltaY > 0 ? step : -step; });
Summary
The above are several common CSS ways to achieve scrolling effects. When using them, choose the most appropriate one according to your specific needs. The way. The implementation using CSS can not only simplify the code, but also make the web page more fluid and dynamic, and also facilitate user experience, component management and debugging.
The above is the detailed content of How to achieve scrolling effect in css. For more information, please follow other related articles on the PHP Chinese website!