Bert Bos | CSS tutorial – backgrounds
From the demo:
p { background-image: url(sunglasses.svg), url(postit.png); background-size:4em auto, 100% 100%; background-position: bottom 0.5em right 0.5em, 0 0; background-repeat: no-repeat, no-repeat; }
From the demo:
div:nth-child(1) { background-size: contain } div:nth-child(2) { background-size: cover }
Values for background-size
:
px
, em
, %
,
auto
('auto' respects the aspect ratio)
contain
(as big as possible with the whole image
visible)
cover
(cover the whole background, but the image
may be clipped in the width or the height)
From the demo :
div:nth-child(1) { border:10px dotted #5f749f; background-size:100px auto, 100% 100%; background-origin: border-box; background-position:85% 10px, top left; }
From the demo:
body{ background-attachment:fixed } div:nth-child(1){ background-attachment:local, local } div:nth-child(2){ background-attachment:local, scroll }
local
= the image scrolls together
with the text of the element
scroll
= the image scrolls only with the window
(January 2013: Opera, ok, Webkit ok, Firefox no)
From the demo:
div:nth-child(1){ background-position: right 30% bottom 3px }
Backgrounds can now be positioned relative to any of the four corners.
(January 2013: Opera ok, Firefox ok, Webkit no)
From the demo:
div:nth-child(1){ background-repeat:round } div:nth-child(2){ background-repeat:space }
round
= whole number of images, slightly resized if
necessary
space
= whole number of images, with possibly some
space between them
(January 2013: Opera rounding errors? Webkit no, Firefox no)
Shorthand:
div:nth-child(1){
background:#c7c7c7 url(postit.png)
top left/cover no-repeat;
}
From the demo
div:nth-child(1){ background-image: linear-gradient(top, tomato, gold); } div:nth-child(10){ background-image: radial-gradient(red, yellow, green); }
(The last example in the demo has a gradient that is shorter than the resolution of the screen. As of Jan. 2013, only Opera implements that correctly.)
Simple: make a document with a background that fills the window with a 2x2 checkerboard pattern. Don't use images, only 'background' and gradients.
Difficult: ditto, but with an 8x8 checkerboard pattern.
Hint: this is how to make a black rectangle:
linear-gradient(black, black)
(may need a “vendor-prefix” in some browsers)