5月11日
CSS 背景全套知识点
一、基础属性
-
背景颜色
css
background-color: 颜色值;
/* 取值:单词、十六进制、rgb、rgba(透明) */
background-color: #f5f5f5;
background-color: rgba(0,0,0,0.3); -
背景图片
css
background-image: url("图片路径"); -
背景平铺 background-repeat
repeat 默认:横竖都平铺
no-repeat 不平铺(只显示一张)
repeat-x 水平平铺
repeat-y 垂直平铺 -
背景位置 background-position
css
/* 方位词 /
background-position: left top;
background-position: center center; / 居中 */
background-position: right bottom;
/* 数值 /
background-position: 50px 30px;
/ 百分比 */
background-position: 50% 50%;
- 背景尺寸 background-size
css
/* 固定宽高 */
background-size: 300px 200px;
/* 等比例铺满 /
background-size: cover; / 全覆盖,可能裁切 /
background-size: contain; / 完整显示,可能留白 */
/* 百分比 */
background-size: 100% 100%;
- 背景附着 background-attachment
scroll 默认:随页面滚动
fixed 固定不动(视差背景常用)
css
background-attachment: fixed;
二、简写写法(最常用)
顺序无严格要求,推荐顺序:
背景色 背景图 平铺 位置 尺寸 附着
css
background: #ccc url(bg.jpg) no-repeat center center / cover fixed;
三、进阶
多重背景
css
background: url(1.png) left top no-repeat,
url(2.png) right bottom no-repeat;
背景透明
background-color: transparent; 完全透明
rgba() 带透明度背景色
渐变背景
css
/* 线性渐变 */
background: linear-gradient(red, blue);
background: linear-gradient(90deg, #fff, #000);
/* 径向渐变 */
background: radial-gradient(red, yellow);
四、高频实用场景
盒子全屏居中背景图
css
.box{
width: 100%;
height: 100vh;
background: url(bg.jpg) no-repeat center;
background-size: cover;
}
图标精灵图定位
用 background-position 移动位置取小图标
固定页面背景
css
body{
background: url(bg.jpg) no-repeat center fixed;
background-size: cover;
}
五、记忆口诀
颜色图片先写上,平铺位置不能忘;
尺寸 cover 全覆盖,fixed 固定不摇晃;
简写一行最省事,开发写码效率强。
浙公网安备 33010602011771号