Dexter Schneider
Dexter Schneider

Reputation: 2520

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.

Upvotes: 1

Views: 982

Answers (3)

cjol
cjol

Reputation: 1495

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;

Upvotes: 2

transparent
transparent

Reputation: 182

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.

Upvotes: 2

Zoltan Toth
Zoltan Toth

Reputation: 47687

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/

Upvotes: 6

Related Questions