2.6 背景属性

CSS背景属性支持颜色、图片、渐变等效果,常用属性如下:

属性 描述 示例
background-color 设置背景色 background-color: #f5f5f5;
background-image 设置背景图片 background-image: url("bg.jpg");
background-repeat 控制图片重复方式 background-repeat: no-repeat;(不重复)、repeat-x(水平重复)
background-position 控制图片位置 background-position: center center;(居中)、20px 30px(距离左上角偏移)
background-size 控制图片尺寸 background-size: cover;(覆盖容器)、contain(完整显示)、100% 100%(拉伸填充)
background 简写属性 background: #f5f5f5 url("bg.jpg") no-repeat center/cover;

渐变背景

通过linear-gradient()radial-gradient()实现渐变效果,无需图片即可创建丰富背景。

案例2-5:渐变背景按钮

html
复制代码
<button class="gradient-btn">点击按钮</button>

<style>
.gradient-btn {
padding: 12px 24px;
border: none;
border-radius: 4px;
color: white;
font-size: 16px;
cursor: pointer;
/* 线性渐变背景 */
background: linear-gradient(135deg, #ff6b6b 0%, #4ecdc4 100%);
/*  hover效果 */
transition: transform 0.2s;
}
.gradient-btn:hover {
transform: scale(1.05); /* 轻微放大 */
}
</style>

注释linear-gradient(135deg, #ff6b6b 0%, #4ecdc4 100%)参数解析:

  • 135deg:渐变方向为从左下角到右上角(0deg为从下到上,90deg为从左到右);
  • #ff6b6b 0%:起始颜色(粉红色),位置从0%开始;
  • #4ecdc4 100%:结束颜色(青绿色),位置到100%结束;
  • 可添加多个颜色节点,如linear-gradient(to right, red, yellow, green)实现多色渐变。