溢出滚动渐变

CSSCSSBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在本实验中,我们将学习如何使用 CSS 为溢出元素添加渐变效果。本实验的目的是为用户创建一个视觉提示,表明还有更多内容需要滚动查看。通过使用 ::after 伪元素和 linear-gradient() 函数,我们可以创建一个从透明渐变到白色的渐变效果,表明还有更多内容可供查看。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL css(("CSS")) -.-> css/BasicConceptsGroup(["Basic Concepts"]) css(("CSS")) -.-> css/CoreLayoutGroup(["Core Layout"]) css(("CSS")) -.-> css/IntermediateStylingGroup(["Intermediate Styling"]) css/BasicConceptsGroup -.-> css/selectors("Selectors") css/CoreLayoutGroup -.-> css/margin_and_padding("Margin and Padding") css/CoreLayoutGroup -.-> css/width_and_height("Width and Height") css/CoreLayoutGroup -.-> css/positioning("Positioning") css/IntermediateStylingGroup -.-> css/backgrounds("Backgrounds") css/IntermediateStylingGroup -.-> css/pseudo_elements("Pseudo-elements") subgraph Lab Skills css/selectors -.-> lab-35228{{"溢出滚动渐变"}} css/margin_and_padding -.-> lab-35228{{"溢出滚动渐变"}} css/width_and_height -.-> lab-35228{{"溢出滚动渐变"}} css/positioning -.-> lab-35228{{"溢出滚动渐变"}} css/backgrounds -.-> lab-35228{{"溢出滚动渐变"}} css/pseudo_elements -.-> lab-35228{{"溢出滚动渐变"}} end

溢出滚动渐变

虚拟机中已经提供了 index.htmlstyle.css

要为溢出元素添加渐变效果,并表明还有更多内容需要滚动,请按照以下步骤操作:

  1. 使用 ::after 伪元素创建一个从 透明 渐变到 白色(从上到下)的 linear-gradient()
  2. 使用 position: absolutewidthheight 在其父元素中定位和调整伪元素的大小。
  3. 使用 pointer-events: none 将伪元素排除在鼠标事件之外,使其后的文本仍可选择/交互。

以下是一个 HTML 和 CSS 代码片段示例:

<div class="overflow-scroll-gradient">
  <div class="overflow-scroll-gradient-scroller">
    Lorem ipsum dolor sit amet consectetur adipisicing elit. <br />
    Iure id exercitationem nulla qui repellat laborum vitae, <br />
    molestias tempora velit natus. Quas, assumenda nisi. <br />
    Quisquam enim qui iure, consequatur velit sit? <br />
    Lorem ipsum dolor sit amet consectetur adipisicing elit.<br />
    Iure id exercitationem nulla qui repellat laborum vitae, <br />
    molestias tempora velit natus. Quas, assumenda nisi. <br />
    Quisquam enim qui iure, consequatur velit sit?
  </div>
</div>
.overflow-scroll-gradient {
  position: relative;
}

.overflow-scroll-gradient::after {
  content: "";
  position: absolute;
  bottom: 0;
  width: 250px;
  height: 25px;
  background: linear-gradient(transparent, white);
  pointer-events: none;
}

.overflow-scroll-gradient-scroller {
  overflow-y: scroll;
  background: white;
  width: 240px;
  height: 200px;
  padding: 15px;
  line-height: 1.2;
}

请点击右下角的“Go Live”以在端口 8080 上运行 Web 服务。然后,你可以刷新“Web 8080”标签页来预览网页。

总结

恭喜你!你已经完成了溢出滚动渐变实验。你可以在 LabEx 中练习更多实验来提升你的技能。