使用background和background-color指定背景色之间的区别是什么?

片段# 1

body { background-color: blue; }

段# 2

body { background: blue; }

当前回答

使用background,你可以设置所有的背景属性,比如:

背景颜色 背景图像 平铺方式 背景位置 等。


使用background-color,你可以指定背景的颜色

background: url(example.jpg) no-repeat center center #fff;

VS.

background-image: url(example.jpg);
background-position: center center;
background-repeat: no-repeat;
background-color: #fff;

更多信息

(见说明:背景-速记属性)

其他回答

背景将取代所有以前的背景颜色,背景图像等规格。这基本上是一种速记,但也是一种重置。

我有时会用它来覆盖以前的模板定制的背景规范,在那里我想要以下:

背景:白色url(images/image1.jpg)左上角重复;

以下是:

背景:黑色;

因此,所有参数(background-image, background-position, background-repeat)将重置为默认值。

假设这是两个不同的属性,在您的特定示例中,结果没有区别,因为background实际上是

背景颜色 背景图像 背景位置 平铺方式 background-attachment background-clip background-origin background-size

因此,除了background-color,使用背景简写,你还可以添加一个或多个值,而不用重复任何其他background-*属性。

选择哪一个本质上取决于你,但也可能取决于你的样式声明的特定条件(例如,如果你从父元素继承其他相关的background-*属性时只需要覆盖background-color,或者如果你需要删除除background-color之外的所有值)。

我发现你不能用background-color设置渐变。

如此:

background:linear-gradient(to right, rgba(255,0,0,0), rgba(255,255,255,1));

这不是:

background-color:linear-gradient(to right, rgba(255,0,0,0), rgba(255,255,255,1));

我注意到在文档中没有看到的一件事是使用 背景:url(“image.png”)

像上面这样的简写,如果图像没有找到,它会发送一个302代码,而不是像你使用的那样被忽略

background-image: url("image.png") 

关于CSS性能:

背景vs Background -color:

比较18个色块在一个页面上渲染100次的小 矩形,一次带有背景,一次带有background-color。

While these numbers are from a single page reload, with subsequent refreshes the render times changed, but the percent difference was basically the same every time. That's a savings of almost 42.6ms, almost twice as fast, when using background instead of background-color in Safari 7.0.1. Chrome 33 appears to be about the same. This honestly blew me away because for the longest time for two reasons: I usually always argue for explicitness in CSS properties, especially with backgrounds because it can adversely affect specificity down the road. I thought that when a browser sees background: #000;, they really see background: #000 none no-repeat top center;. I don't have a link to a resource here, but I recall reading this somewhere.

参考:https://github.com/mdo/css-perf#background-vs-background-color