2

I have a linear gradient: 2em red, 4em yellow

.bar {
    background: repeating-linear-gradient(90deg, red 0, red 2em, yellow 2em, yellow 6em);
    background-position-x: 0em;
}

If I move the gradient one 1em to the right via background-position-x: 1em;

I expect that that my gradient will start with a 1em yellow block and a 2em red block.

Instead it grabs the previous last block at the end of the div which was red. So I get then 3em red, 4em yellow, which breaks my rule.

Here is a demo: http://codepen.io/anon/pen/XXmOPB?editors=110

Harry
  • 87,580
  • 25
  • 202
  • 214
timaschew
  • 16,254
  • 6
  • 61
  • 78

1 Answers1

3

Repeating gradients have cyclic repetition and so without an explicit background-size setting added you'd have to treat it as though tiles of 31em are placed one next to the other. So when background's position in x-axis is set as 1em, it kind of becomes like -30em to 1em is one tile, 1em to 32em will be another tile and so on. This the reason why you see the last 1em of the first tile (which is red) and the rest of the second tile (which 6em * 5) as the background image within the container.

The reason for the background gradient image's size being taken as 31em is discussed in the answer I had provided here.


The solution to your problem is to explicitly set the background-size in X-axis as equal to your actual gradient size.

.foo div.bar {
  width: 31em;
  height: 2em;
}
.foo2 div.bar {
  width: 33em;
  height: 2em;
}
.bar {
  background: repeating-linear-gradient(90deg, red 0, red 2em, yellow 2em, yellow 6em);
  background-size: 6em 100%;
  background-position-x: 1em;
}

/* Just for demo */
div {
  margin: 10px;
}
<div class="foo">
  <div class="bar">
  </div>
</div>
<div class="foo2">
  <div class="bar">
  </div>
</div>

Also, please note that background-position-x and background-position-y were initially proposed for CSS3 (and got rejected). It is now approved for Level 4 but to support the older browsers also it is better to use the shorthand property like given below. I just verified that some older Firefox versions do not support background-position-x.

background-position: 1em 0em;
Community
  • 1
  • 1
Harry
  • 87,580
  • 25
  • 202
  • 214