用 CSS 做一个“通知条 + 渐变按钮”的前端小示例(含代码)

用 CSS 做一个“通知条 + 渐变按钮”的前端小示例(含代码)

做后台或营销页时,我最常用的一个组件就是“顶部通知条(Notice Bar)+ 渐变按钮”。它成本低、可复用、移动端也容易适配,而且不需要任何 JS 就能做出不错的交互感。下面给你一个可以直接复制使用的纯前端示例:包含通知条、信息图标、关闭按钮、以及一个带 hover 动效的渐变按钮。


✅ HTML(结构示例)

<div class="notice-bar" role="status">
  <div class="notice-left">
    <span class="notice-icon">⚡</span>
    <span class="notice-text">
      系统已完成缓存刷新,部分页面将在 1 分钟内同步更新。
    </span>
  </div>

&lt;div class="notice-right"&gt; <a>查看详情</a> &lt;button class="notice-close" aria-label="关闭"&gt;✕&lt;/button&gt; &lt;/div&gt; &lt;/div&gt;


✅ CSS(核心样式 + 动效)

/ 基础重置(可选) /
* { box-sizing: border-box; }
body { margin: 0; font-family: system-ui, -apple-system, Segoe UI, Roboto, Arial; }

/ 通知条容器 / .notice-bar { position: sticky; top: 0; z-index: 999; display: flex; align-items: center; justify-content: space-between; gap: 12px;

padding: 12px 14px; border-bottom: 1px solid rgba(255,255,255,0.12);

background: linear-gradient(90deg, #141e30 0%, #243b55 100%); color: #fff; }

/ 左侧内容 / .notice-left { display: flex; align-items: center; gap: 10px; min-width: 0; }

.notice-icon { width: 28px; height: 28px; display: grid; place-items: center;

background: rgba(255,255,255,0.12); border: 1px solid rgba(255,255,255,0.18); border-radius: 10px; flex: 0 0 auto; }

.notice-text { font-size: 14px; line-height: 1.4; opacity: 0.92;

/ 文本过长自动省略 / overflow: hidden; white-space: nowrap; text-overflow: ellipsis; }

/ 右侧区域 / .notice-right { display: flex; align-items: center; gap: 10px; flex: 0 0 auto; }

/ 渐变按钮 / .notice-btn { text-decoration: none; font-size: 14px; font-weight: 600; color: #0b1220;

padding: 9px 12px; border-radius: 12px;

background: linear-gradient(135deg, #fbd786 0%, #f7797d 100%); box-shadow: 0 8px 18px rgba(0,0,0,0.25);

transform: translateY(0); transition: transform .18s ease, filter .18s ease; }

.notice-btn:hover { transform: translateY(-1px); filter: brightness(1.06); }

/ 关闭按钮 / .notice-close { width: 34px; height: 34px; border: 1px solid rgba(255,255,255,0.18); background: rgba(255,255,255,0.08); color: #fff;

border-radius: 12px; cursor: pointer; transition: background .18s ease, transform .18s ease; }

.notice-close:hover { background: rgba(255,255,255,0.14); transform: scale(1.03); }

/ 移动端适配 / @media (max-width: 540px) { .notice-text { max-width: 210px; } .notice-btn { padding: 8px 10px; } }


✅ 说明(怎么用最省事)

  • 你可以把 .notice-bar 放在页面顶部(或 header 下面),它 position: sticky 会自动吸顶。
  • 文本太长会自动省略,避免移动端撑爆布局。
  • 如果你想让关闭按钮真的关闭通知条,可以加一点点 JS(你没要求我就不写),或者用 CSS 的 :has() 技巧做纯 CSS 关闭(需要新浏览器支持)。

评论 0