简体   繁体   中英

Setting background color and background image in CSS

I have a problem with setting a background image over my background color: Here is my example so that you can see what I mean: JSFiddle

Now here is the functional CSS part:

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

As you can see in the JSFiddle, the background image repeats. If I use no-repeat as a property, the image disappears.

Also, I want the background image to float to the right, and should the image be bigger than the containing div, how to I make it fit proportionally? - Like you would make an image tag <img/> fit by using width: 100% and height: 100% ?

I don't want to use an HTML image tag, it would be much easier but there are several reasons I do not want to use it.

Try this - http://jsfiddle.net/vmvXA/17/

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

and to make the background image not exceed its parent container you can use background-size: contain - http://jsfiddle.net/vmvXA/22/

You can't just add no-repeat to background-image , because background-image is a specific property that only refers to the image itself. If you want to add it all in one declaration, then set background :

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

or keep it all separate, up to you:

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;

Here's the fiddle .

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

To make the code shorter, it is possible to specify all the settings in one single property. This is called a 'shorthand property'.

To make all pictures fit inside it's parent add the style property background-size:contain; .

Updated the fiddle.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM