使用background和background-color指定背景色之间的区别是什么?
片段# 1
body { background-color: blue; }
段# 2
body { background: blue; }
使用background和background-color指定背景色之间的区别是什么?
片段# 1
body { background-color: blue; }
段# 2
body { background: blue; }
当前回答
Background是背景颜色和其他一些背景相关的东西的快捷方式,如下所示:
background-color
background-image
background-repeat
background-attachment
background-position
阅读下面来自W3C的声明:
背景-速记属性用于缩短代码 也可以指定所有的背景属性在一个单一 财产。这被称为速记属性。 background的简写属性是background:
body {
background: white url("img_tree.png") no-repeat right top;
}
当使用速记属性时,属性值的顺序是:
背景颜色 背景图像 平铺方式 background-attachment 背景位置 如果缺少一个属性值,这并不重要 其他的都是这个顺序。
其他回答
你可以做一些非常巧妙的事情一旦你理解了你可以利用继承。然而,首先让我们了解一下这个文档的背景:
使用CSS3,你可以为元素应用多个背景。这些都是 与你提供的第一个背景相叠加 最后一个背景列在后面。只有最后一个背景 可以包含背景色。
所以当有人这样做的时候:
background: red;
他将背景色设置为红色,因为红色是最后列出的值。
当一个人这样做时:
background: linear-gradient(to right, grey 50%, yellow 2%) red;
红色仍然是背景色,但是你会看到渐变。
.box { 这个特性:50%; 宽度:200 px; 身高:200 px; 背景:线性渐变(向右,灰色50%,黄色2%)红色; } {前.box:: 内容:“”; 显示:块; margin-left: 50%; 高度:50%; 边界半径:0 100% 100% 0 / 50%; transform: translateX(70px) translateY(-26px) rotate(325deg); 背景:继承; } < div class = "盒子" > < / div >
现在对background-color做同样的事情:
.box { 这个特性:50%; 宽度:200 px; 身高:200 px; 背景:线性渐变(向右,灰色50%,黄色2%)红色; } {前.box:: 内容:“”; 显示:块; margin-left: 50%; 高度:50%; 边界半径:0 100% 100% 0 / 50%; transform: translateX(70px) translateY(-26px) rotate(325deg); background - color:继承; } < div class = "盒子" > < / div >
发生这种情况的原因是因为当我们这样做的时候:
background: linear-gradient(to right, grey 50%, yellow 2%) #red;
最后一个数字设置背景颜色。
然后在我们从background继承之前(然后我们得到渐变)或者背景颜色,然后我们得到红色。
没有区别。两者将以同样的方式工作。
CSS背景属性用于定义背景效果 一个元素。 用于背景效果的CSS属性: 背景颜色 背景图像 平铺方式 background-attachment 背景位置
Background属性包括所有这些属性,您可以将它们写在一行中。
关于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
比较18个色块在一个页面上渲染100次的小 矩形,一次带有背景,一次带有background-color。
我重新创建了CSS性能实验,现在的结果明显不同。
background
Chrome 54: 443(µs/div)
Firefox 49: 162(µs/div)
边缘10:56(µs/div)
background-color
Chrome 54: 449(µs/div)
Firefox 49: 171(µs/div)
边缘10:58(µs/div)
如你所见,几乎没有区别。
我注意到在文档中没有看到的一件事是使用 背景:url(“image.png”)
像上面这样的简写,如果图像没有找到,它会发送一个302代码,而不是像你使用的那样被忽略
background-image: url("image.png")