Css background: offset for repeating-linear-gradient

4.1k views Asked by At

I have drawn a grid as a repeating background of a <div> the following way in SASS:

background-image:
  repeating-linear-gradient(0deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
  repeating-linear-gradient(-90deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
  repeating-linear-gradient(0deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size),
  repeating-linear-gradient(-90deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size);

It renders the following way:

Bad

But I want it to render with an offset of 15px to the left (or an offset of 4 * $minor-grid-size + 15px to the right), ie:

enter image description here

Now I can't use margin-left, because it will also offset the elements inside of the <div> tag and I don't want that, see the Fiddle here (don't pay attention to the JS).

I only want the background to have an offset.

2

There are 2 answers

0
Kosh On BEST ANSWER

You might use background-position property.

.repeating-grid {
  position: absolute;
  top: 0; bottom: 0;
  left: 0; right: 0;
  background-size: $major-grid-size $major-grid-size;
  background-image:
    repeating-linear-gradient(0deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
    repeating-linear-gradient(-90deg, $major-grid-color, $major-grid-color $major-grid-weight, transparent $major-grid-weight, transparent $major-grid-size),
    repeating-linear-gradient(0deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size),
    repeating-linear-gradient(-90deg, $minor-grid-color, $minor-grid-color $minor-grid-weight, transparent $minor-grid-weight, transparent $minor-grid-size);

  background-position: 15px 0;
}
0
Mike On

I had issues with a negative background-position causing the end of the repeating pattern to be cut off:

background-image: repeating-linear-gradient(90deg, red, red 200px, blue 200px, blue 400px);
background-position: -50px -50px;

background-position

I found that using negative offsets in repeating-linear-gradient fixed the problem:

background-image: repeating-linear-gradient(90deg, red -50px, red 150px, blue 150px, blue 350px);

enter image description here