Search code examples
csslinear-gradients

Can a linear gradient be a different size than its container?


In this very simple example, is it possible in CSS to:

  1. Have the black lines not be as wide as the gray area?
  2. Use a repeating linear gradient rather than repeat each black/transparent section?
  3. Have the black lines centered in the height of the gray area without knowing in advance how tall the gray area is?

I can make a second more narrow div to hold the black lines as a repeating linear gradient and position it in the center of the gray div; but wondered if it is possible with one div.

I see that they can make complex plaid designs with gradients and all kinds of intricate things; but I'm not at all all artistic and a few perpendicular lines is a challenge.

Thanks for any direction you may be able to provide.

:root { --start: 8.0rem; }
html { font-size: 62.5% }
div {
  width: 50px;
  height: 20.0rem;
  background-color: rgb(200,200,200);
  background-image: linear-gradient( to bottom,
     transparent var(--start),
     black var(--start), black calc(var(--start) + 0.1rem),
     transparent calc(var(--start) + 0.1rem), transparent calc(var(--start) + 0.3rem),
     black calc(var(--start) + 0.3rem), black calc(var(--start) + 0.4rem),
     transparent calc(var(--start) + 0.4rem), transparent calc(var(--start) + 0.6rem),
     black calc(var(--start) + 0.6rem), black calc(var(--start) + 0.7rem),
     transparent calc(var(--start) + 0.7rem), transparent calc(var(--start) + 0.9rem),
     black calc(var(--start) + 0.9rem), black calc(var(--start) + 1.0rem),
     transparent calc(var(--start) + 1.0rem), transparent calc(var(--start) + 1.2rem),
     black calc(var(--start) + 1.2rem), black calc(var(--start) + 1.3rem),
     transparent calc(var(--start) + 1.3rem), transparent calc(var(--start) + 1.5rem),
     black calc(var(--start) + 1.5rem), black calc(var(--start) + 1.6rem),
     transparent calc(var(--start) + 1.6rem), transparent
   );
  }
<div></div>


Solution

  • You can define a size and position for a gradient

    :root { --start: 8.0rem; }
    html { font-size: 62.5% }
    div {
      width: 50px;
      height: 20.0rem;
      background: 
        repeating-linear-gradient(black 0 0.1rem,#0000 0 0.3rem)
        center/  /* position */
        60% 1.6rem /* size (width height) */
        no-repeat /* don't repeat */
        rgb(200,200,200); /* background color */
      }
    <div></div>

    Related:

    Error: CSS: background: / is an incorrect operator

    Issues with "background-position" in "background" shorthand property