在CSS中设置背景颜色和背景图像

时间:2012-08-10 19:56:21

标签: css css3

我在背景颜色上设置背景图片时出现问题:以下是我的示例,以便您了解我的意思:JSFiddle

现在这里是功能性的CSS部分:

#tancan{
    background-color: #ebebeb;
    background-image: url('http://lamininbeauty.co.za/images/products/tancan2.jpg');
}

正如您在JSFiddle中看到的那样,背景图像重复出现。如果我使用no-repeat作为属性,图像就会消失。

另外,我希望背景图像向右浮动,如果图像比包含div大,我该如何使它按比例调整? - 就像您使用<img/>width: 100%制作图片代码height: 100%一样?

我不想使用HTML图片代码,这会更容易,但有几个原因我不想使用它。

3 个答案:

答案 0 :(得分:6)

试试这个 - http://jsfiddle.net/vmvXA/17/

#tancan {
    background: #ebebeb url('http://lamininbeauty.co.za/images/products/tancan2.jpg') no-repeat top right;
}

要使背景图片不超过其父容器,您可以使用background-size: contain - http://jsfiddle.net/vmvXA/22/

答案 1 :(得分:2)

您不能只将no-repeat添加到background-image,因为background-image是一个只引用图片本身的特定属性。如果要将其全部添加到一个声明中,请设置background

background: url('http://lamininbeauty.co.za/images/products/tancan2.jpg') #ebebeb no-repeat top right;

或将它们全部分开,由您决定:

background-color: #ebebeb;
background-image: url('http://lamininbeauty.co.za/images/products/tancan2.jpg');
background-repeat: no-repeat;
background-position:top right;
background-size: contain;

答案 2 :(得分:2)

Here's the fiddle

    background:#ebebeb url('http://lamininbeauty.co.za/images/products/tancan2.jpg') no-repeat right top;

为了缩短代码,可以在一个属性中指定所有设置。这被称为“速记属性”。

要使所有图片都适合它的父级,请添加样式属性background-size:contain;

更新了小提琴。