css制作背景
使用纯色背景
通过 background-color 属性设置纯色背景,支持颜色名称、十六进制、RGB 或 HSL 值。
body {
background-color: #f0f0f0; /* 浅灰色 */
}
使用图片背景
通过 background-image 属性添加图片背景,结合 background-size 和 background-repeat 控制显示效果。
body {
background-image: url("image.jpg");
background-size: cover; /* 覆盖整个容器 */
background-repeat: no-repeat; /* 禁止重复 */
}
渐变背景
使用 linear-gradient 或 radial-gradient 创建渐变效果。
body {
background: linear-gradient(to right, #ff9966, #ff5e62);
}
多背景叠加
通过逗号分隔多个背景属性,实现叠加效果。
body {
background:
linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.5)),
url("image.jpg") center/cover no-repeat;
}
固定背景(视差效果)
使用 background-attachment: fixed 让背景固定,内容滚动时产生视差效果。
body {
background-image: url("image.jpg");
background-attachment: fixed;
}
背景裁剪与定位
通过 background-clip 和 background-origin 控制背景的显示区域和起始位置。
div {
background-clip: padding-box; /* 背景仅在内边距区域显示 */
background-origin: border-box; /* 从边框区域开始绘制 */
}
动态背景(动画)
结合 CSS 动画实现动态背景效果。
@keyframes gradientShift {
0% { background-position: 0% 50%; }
50% { background-position: 100% 50%; }
100% { background-position: 0% 50%; }
}
body {
background: linear-gradient(45deg, #ff9a9e, #fad0c4, #fbc2eb);
background-size: 200% 200%;
animation: gradientShift 5s ease infinite;
}






