带有1px白色的CSS背景条纹,其余为透明

时间:2017-09-14 13:49:59

标签: css css-gradients

我已经阅读过CSS背景条纹教程,但我似乎没有找到解决这个问题的方法。如果我想要1px宽的对角白线与大约10px宽的透明条纹交替怎么办?像这样:

enter image description here

我现在的代码是:

.stripes {
    background: repeating-linear-gradient(
      45deg,
      transparent 46%, #fff 49%, #fff 51%, transparent 55%
    );
    width: 180px;
    height: 56px;
    z-index: 99;
    position: absolute;
    left: 0;
    top: 0;
}

但是这会产生模糊,粗糙的白线。我是这个概念的新手。

1 个答案:

答案 0 :(得分:0)

要获得精确的像素尺寸,您可以使用像素而不是百分比:

body {
    background: #222;
}

.stripes {
    background: repeating-linear-gradient(
      -75deg,
      #fff, /* White, starting at pixel 0 */
      #fff 1px,  /* White, continuing to pixel 1 */
      transparent 1px, /* Transparent beginning at pixel 1 */
      transparent 10px /* Transparent ending at pixel 11 (10 + 1) */
    );
    width: 180px;
    height: 56px;
    z-index: 99;
    position: absolute;
    left: 0;
    top: 0;
}

.stripes2px {
    background: repeating-linear-gradient(
      -75deg,
      #fff, /* White, starting at pixel 0 */
      #fff 2px,  /* White, continuing to pixel 2 */
      transparent 2px, /* Transparent beginning at pixel 2 */
      transparent 12px /* Transparent ending at pixel 14 (12 + 2) */
    );
    top: 56px;
}

.stripes-fade {
    background: repeating-linear-gradient(
      -75deg,
      #fff, /* White, starting at pixel 0 */
      #fff 1px,  /* White, continuing to pixel 1 */
      transparent 2px, /* Transparent beginning at pixel 2 */
      transparent 10px /* Transparent ending at pixel 12 (10 + 2) */
    );
    top: 112px;
}
<div class="stripes"></div>
<div class="stripes stripes2px"></div>
<div class="stripes stripes-fade"></div>

另一种方法,但给出相同的结果。与浏览器渲染方式有关(无抗锯齿):

body {
    background: #222;
}

.stripes {
    width: 180px;
    height: 56px;
    z-index: 99;
    position: absolute;
    left: 0;
    top: 0;
    overflow: hidden;
}

.stripes:before {
    content: '';
    display: block;
    background: repeating-linear-gradient(
      0deg,
      #fff, /* White, starting at pixel 0 */
      #fff 1px,  /* White, continuing to pixel 1 */
      transparent 1px, /* Transparent beginning at pixel 1 */
      transparent 10px /* Transparent ending at pixel 11 (10 + 1) */
    );
    position: absolute;
    /* Just a bunch of random numbers to get it to cover - no thought went into these. */
    top: -100%;
    left: -200%;
    width: 400%;
    height: 1000%;
    transform: rotate(-75deg);
}
<div class="stripes"></div>