background介绍-图片篇

1,631 阅读3分钟

backgroud属性

background在css中是一个常见的背景设置,这篇文章主要是详细总结下background的用法。在MDN中的介绍如下:

background 是一种 CSS 简写属性,用于一次性集中定义各种背景属性,包括 color, image, origin 与 size, repeat 方式等等。

普通用法

首先介绍下background的简单用法,先新建一个div

<div class="box-color"></div>

background-color属性

Background-color属性给元素设置一个背景色。

.box-color {
    width: 100px;
    height: 100px;
    background-color: #ea7070;
}

效果展示:

background-image属性

单张背景图片

给div设置一张背景图片,从网上照了一张图片。 先写一段html代码:

<div class="box"></div>

.box {
  width: 200px;
  height: 200px;
  background-image: url('src/1.jpg')
}

效果展示:

这时,在box中的背景图片并没有完全展示出来,只是展示出来原图片的一部分。这是因为background-size属性默认值为auto,属性值为auto时,图片不拉伸,只裁剪一部分,所以显不出来完整的图片。如果想要改变图片在box中的展示效果,可以改变backgrround-size的值。

background-size设置背景图片大小。图片可以保有其原有的尺寸,或者拉伸到新的尺寸,或者在保持其原有比例的同时缩放到元素的可用空间的尺寸。

background-size: auto(default) || contain || cover || 30% || 200px 100px;

设置不同的background-size的值得背景图片效果:

设置多张背景图片

当我们需要多张图片为背景时,可以通过background属性设置多张图片。找的第二张素材图片,是一张月亮图片。

现在我们想要实现,月亮在粉色的天空上的背景效果。background-image可以设置多张图片,中间以逗号隔开即可。

.box {
  width: 200px;
  height: 400px;
  background-image: url('../img/1.jpg'), url('../img/2.jpg');
}

这时可以发现月亮的背景图片被覆盖了,这时需要设置background-blend-mode属性。

background-blend-mode CSS属性定义该元素的背景图片,以及背景色如何混合。

background-blend-mode定义了多张图片混合的模式,可以理解为ps中的图层的混合模式。

  1. 此处可以给两张图片设置"正片叠底"模式:background-blend-mode: multiply, multiply;
  2. 再设置相关background-sizebackground-position调整位置,月亮背景图片就完成了。
.box {
            width: 200px;
            height: 400px;
            background-image: url('../img/1.jpg'), url('../img/2.jpg');
            background-size: 100% 100%, 60px 60px;
            background-position: left top, 70px 40px;
            background-repeat: no-repeat, no-repeat;
            background-blend-mode: multiply, multiply;
}

效果图如下:

背景图片和颜色共用

因为background是一个简写属性,可以一次性声明定义一个或者多个属性:background-clipbackground-clorbackground-imagebackground-originbackground-positionbackground-repeatbackground-sizebackground-attachment

按照直接声明相关属性即可:

.box {
        width: 100%;
        height: 100px;
        background: url("../img/2.jpg") aliceblue repeat-y fixed;
}

就可以得到左侧一张背景图,右侧天蓝色的样式效果。

参考资料

  1. 更丰富的网页多图层效果:css混合模式