Backgrounds and linear gradients in CSS
26 Backgrounds and gradients
easyGive three panels a flat colour, a two-stop linear gradient and a repeating stripe. Keep the text on all three readable, and draw the stripes with CSS rather than an image file.
Stuck? Three hints, smallest first
- 1.
linear-gradient()is a value forbackground-image, so it stacks like one. - 2. The angle comes first:
135degruns from the top left corner downwards. - 3.
repeating-linear-gradient()with hard stops gives you stripes with no image and no request.
<div class="panel flat">A flat colour</div>
<div class="panel fade">A two-stop gradient</div>
<div class="panel stripe">Repeating stripes</div>
.panel {
padding: 16px;
margin-bottom: 8px;
border-radius: 8px;
color: #ffffff;
font-size: 0.9rem;
}
.flat { background-color: #0b3a8f; }
.fade {
background-image: linear-gradient(135deg, #0b3a8f 0%, #3055d8 100%);
}
/* Hard stops, so each colour ends exactly where the next begins. The text sits
on the darker of the two, which is the one that has to clear contrast. */
.stripe {
background-image: repeating-linear-gradient(
45deg,
#0b3a8f 0 12px,
#17307a 12px 24px
);
}
8 checks that prove this answer
Assertions, run in the browser. The markup and styles above are handed to them
as html and css, so press Run and each check prints
ok. The build fails if a single one fails.
test('a flat background colour', /background-color:\s*#0b3a8f/.test(css), true);
test('a linear gradient with an angle', /linear-gradient\(\s*135deg/.test(css), true);
test('and two explicit stops', /#0b3a8f 0%[\s\S]*#3055d8 100%/.test(css), true);
test('the stripes repeat', /repeating-linear-gradient/.test(css), true);
test('with hard stops rather than a fade', /#0b3a8f 0 12px/.test(css), true);
test('gradients are background-image values, not colours', (css.match(/background-image:/g) || []).length, 2);
test('no image file is referenced at all', /url\(/.test(css), false);
test('white text on dark panels throughout', /color:\s*#ffffff/.test(css), true);
Output
A gradient is an image, not a colour, which explains two things people trip over: it belongs in background-image, and you can stack several with commas the way you would stack images. Hard stops — giving one colour an end position and the next the same start position — turn a gradient into flat bands, which is how you draw stripes, checks and rules with no file and no request. The contrast note is not decoration: text over a gradient has to clear AA against the lightest part it covers, so it is worth picking the range deliberately rather than eyeballing the middle.