CSS 设置渐变背景 CSS 设置渐变边框

一、css渐变背景添加透明度opacity

css渐变背景经常会在项目开发中遇到,此时UI如果给出的是单一的渐变背景(没有背景透明度),这个我们会很快的写出代码,如下:

html 复制代码
<div class="btn">这是一个按钮</div>
css 复制代码
.btn {
  background: linear-gradient(to right, #8B78E6, #50A5A5);
  color: #fff;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  transition: background 0.3s ease;
}

.btn:hover {
  background: linear-gradient(to right, #50A5A5, #8B78E6);
}

但偶尔的时候UI会给煎饼的背景色添加一个透明度,但是使用opacity属性会导致文本也会有透明度,接下来给出我的解决办法

css 复制代码
.btn {
  position: relative;
  color: #fff;
  padding: 10px 20px;
  font-size: 16px;
  border-radius: 5px;
  border: none;
  cursor: pointer;
  transition: background 0.3s ease;
  z-index: 0;
}

.btn:hover {
  background: linear-gradient(to right, #50A5A5, #8B78E6);
}

.btn::after{
  position: absolute;
  z-index: -1;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  content: "";
  opacity: 0.3;
  background: linear-gradient(to right, #8B78E6, #50A5A5);
}

二、css按钮添加渐变边框

1、使用border-image

css 复制代码
.btn {
  border: 4px solid;
  border-image: linear-gradient(to right, #8f41e9, #578aef) 1;
}

/* 或者 */
.btn {
  border: 4px solid;
  border-image-source: linear-gradient(to right, #8f41e9, #578aef);
  border-image-slice: 1;
}

2、使用伪元素

html 复制代码
<div class="border-box">
   <div class="content">
        这是一个使用伪元素实现渐变边框的按钮
   </div>
</div>
css 复制代码
.border-box {
  border: 1px solid transparent;
  border-radius: 16px;
  position: relative;
  color: #F2B05E;
  background-color: #fff;
  background-clip: padding-box; /*important*/
}

.border-box::before {
  content: '';
  position: absolute;
  top: 0;
  right: 0;
  left: 0;
  bottom: 0;
  z-index: -1;
  margin: -1px;
  border-radius: inherit; /*important*/
  background: linear-gradient(to right, #8F41E9, #578AEF);
}

3、使用单个元素background-clipbackground-originbackground-image

css 复制代码
.border-box {
  border: 1px solid transparent;
  border-radius: 16px;
  color: #F2B05E;
  background-clip: padding-box, border-box;
  background-origin: padding-box, border-box;
  background-image: linear-gradient(to right, #fff,#fff), linear-gradient(90deg, #8F41E9, #578AEF);
}

background-clip 、background-origin属性添加了解释链接,没弄清的童鞋可以点击看下~

分享完毕~~

相关推荐
AZaLEan__9 小时前
前端移动端适配与 Bootstrap
前端·bootstrap·html
padane2211 小时前
gmssl编译wasm
ubuntu·html·密码学·wasm·js
ZC跨境爬虫11 小时前
跟着 MDN 学CSS day_21:(图像溢出控制与表单元素样式定制)
前端·javascript·css·ui·交互
RD_daoyi14 小时前
Google 网站收录全流程解析:抓取、索引与排名机制详解
前端·javascript·人工智能·学习·搜索引擎·html
高心星14 小时前
鸿蒙6.0应用开发——Web组件的生命周期
html·web组件·arkweb·鸿蒙6.0·harmonyos6.0
暗冰ཏོ14 小时前
2026前端开发资源整理大全:从基础学习到工程化实战的完整导航
前端·javascript·css·前端框架·html
dsyyyyy110115 小时前
CSS继承性
前端·css·tensorflow
Rauser Mack19 小时前
编程纯小白,五分钟用AI做了个小游戏(附Prompt)
人工智能·python·html·prompt·ai编程
ZC跨境爬虫19 小时前
跟着 MDN 学CSS day_23:(表单与表格综合样式化实战)
前端·javascript·css·ui·html·tensorflow
hhzz21 小时前
从混乱 HTML 到干净表格:用智能采集 API 啃下非规范电商页面
前端·html·网络爬虫