如何不重复具有多个响应背景的背景规范

How to not to repeat background specs with multiple responsive backgrounds

这是当前代码:

.description-1-section{
  background: linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%), url('../images/fondo-1-s.jpg');
  background-repeat: no-repeat;
  background-size: cover;
  color: $white;

  @include mq($medium-up){
    background: linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%), url('../images/fondo-1-m.jpg');
    background-repeat: no-repeat;
    background-size: cover;
  }

  @include mq($medium-aux-up){
    background: linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%), url('../images/fondo-1.jpg');
    background-repeat: no-repeat;
    background-size: cover;
  }
}

我发现它正在使用多个 bgs(在本例中为渐变 + 图像),当为断点目的更新某些值时,似乎我必须重复附件指令(background-repeat: no-repeat; background-size: cover;)。

在这个用例中有没有办法避免这种重复?

使用 CSS 变量并将背景大小放入 shorthand 中并重复。您还将避免重复渐变:

.description-1-section{
  background: linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%), var(--im,url('../images/fondo-1-s.jpg')) center/cover no-repeat;
  color: $white;

  @include mq($medium-up){
    --im: url('../images/fondo-1-m.jpg');
  }

  @include mq($medium-aux-up){
    --im: url('../images/fondo-1.jpg');
  }
}

要测试的工作示例:

.description-1-section{
  background: 
   linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%), 
   var(--im,url('https://picsum.photos/id/1/600/200')) center/cover no-repeat;
  height:50px;
}
.md{
    --im: url('https://picsum.photos/id/10/600/200');
  }

.ml{
    --im:url('https://picsum.photos/id/12/600/200');
  }
}
<div class="description-1-section">

</div>
<div class="description-1-section md">

</div>
<div class="description-1-section ml">

</div>

使用 shorthand background 重置 未单独列出的隐式属性。

The background shorthand CSS property sets all background style properties at once, such as color, image, origin and size, or repeat method.

MDN

我建议只使用 background-image 而不是

background-image: 
  linear-gradient(0deg, #464646 30.75%, rgba(51, 51, 51, 0) 100%),
  url('../images/fondo-1-s.jpg');