Anindya Basu
Anindya Basu

Reputation: 659

CSS background shorthand property not working with background-size

When I try to combine several lines of CSS into one when styling a background image like so:

background: url("img/background.jpg") cover no-repeat;

It doesn't work; however, when I move the cover and no-repeat onto their own lines

background: url("img/background.jpg");
background-size: cover;
background-repeat: no-repeat;

The image works just fine. Any hints or ideas on what's going wrong? I often notice this problem with things like padding and margins as well.

Upvotes: 13

Views: 4874

Answers (5)

austinabraham_a
austinabraham_a

Reputation: 11

If one of the properties in the shorthand declaration is the bg-size property, you must use a / (slash) to separate it from the bg-position property, e.g. background:url(smiley.gif) 10px 20px/50px 50px; will result in a background image, positioned 10 pixels from the left, 20 pixels from the top, and the size of the image will be 50 pixels wide and 50 pixels high.

background: bg-color bg-image position/bg-size bg-repeat bg-origin bg-clip bg-attachment initial|inherit;

Upvotes: 0

Lunayyko
Lunayyko

Reputation: 21

I use this for the logo

background: url('img/logo.png') center center / contain no-repeat;

and it works quite well.

Upvotes: 0

Hastig Zusammenstellen
Hastig Zusammenstellen

Reputation: 4450

If in longhand you're using a single value keyword (top, left, etc.) and letting the unwritten one default to center it won't work in shorthand. You need to specify both keyword values.

background: url("image.jpg");
background-position: left;
background-size: cover;

In shorthand you will have to specify both values..

background: url("image.jpg") left center / cover;

Or both center..

background: url("image.jpg");
background-position: center;
background-size: cover;

background: url("image.jpg") center center / cover;

Upvotes: 3

BoltClock
BoltClock

Reputation: 724132

The background shorthand requires that you also set background-position in order to set background-size. You can find the grammar for the background shorthand in the spec, but in a nutshell the syntax for the two properties is

<bg-position> [ / <bg-size> ]

which means "background-position, optionally followed by a forward slash then background-size" (the usual optional-whitespace rules apply)

If you do not need to change background-position to a different value, the initial value is 0 0 (zero on both axes):

background: url("img/background.jpg") 0 0 / cover no-repeat;

Upvotes: 17

Super Hornet
Super Hornet

Reputation: 2907

background-size should not be included in background because it is not recognized by browsers.

Upvotes: 2

Related Questions