background整理

108 阅读2分钟

background属性设置元素的背景色及背景图

background 在一个声明中可以设置所有背景属性

依次为: background-color background-img background-repeat background-attachment background-position/background-size如;

div {
    // 推荐这种写法
    background: red url(./pic.png) no-repeat fixed center/100% 100%;
}

可以打乱顺序 或者不传其中的一个

background-color 背景颜色 transparent 表示全透明
background-img 背景图片 url
background-repeat 图像是否及如何重复 默认为repeat 即x和y方向上都会重复 一般使用设置no-repeat
background-attachment 背景图像是否固定或者随着页面的其余部分滚动 默认 scroll 另一个为fixed
background-position 图片起始位置 默认左上
background-size 图片大小 只能放在position后面,用/隔开

小应用1:当设计给的背景图片只有一部分有颜色一部分透明,但是整体的背景是有一个背景色时,需要背景图片和背景色同时作用,此时刚好用到background的上述写法实现效果:

div {
    // 此时 背景图片和背景颜色同时作用在背景区域元素上
    background: red url(./pic.png) no-repeat;
}

background-size 图片大小

div {
    // 此时表示背景图片的宽高为背景元素的100%
    background-size: 100% 100%; // 宽和高 只设置其中一个,另一个为auto;
}

image.png

cover 保持图片的纵横比 缩放至覆盖背景定位元素的最小大小

image.png contain 缩放至适合背景区域的最大大小

image.png 小应用2:一般情况下(标准情况下使用)contain,但是在设备宽高比不一定但是不会差太多时,可以使用100%,来覆盖背景元素。

div {
    // 此时表示背景图片的宽高为背景元素的100%,放弃图片本身的宽高比,随着背景元素缩放而缩放,可能会导致失真
    background-size: 100% 100%;
    // 对失真要求高 又必须覆盖的,可选cover
    background-size: cover;
    // 根据实际情况选择
}

小应用3:可以设置多层背景,通过「,」隔开。

div {
    // 实现多层背景的唯一写法
    background: red url(./pic.png) no-repeat fixed center/100% 100%, url(./pic2.png);
}

background-clip 规定背景的绘制区域

属性值:border-box|padding-box|content-box 背景被裁剪到边框border|背景被裁剪到padding|背景被裁剪到内容

.box {
  width: 400px;
  height: 400px;
  border: 30px double red;
  padding: 30px;
  background: yellow;
  background-clip: border-box;
}

image.png

.box {
  width: 400px;
  height: 400px;
  border: 30px double red;
  padding: 30px;
  background: yellow;
  background-clip: padding-box;
}

image.png

.box {
  width: 400px;
  height: 400px;
  border: 30px double red;
  padding: 30px;
  background: yellow;
  background-clip: content-box;
}

image.png

background-blend-mode 定义每个背景层(颜色和/图像)的混合模式