SASS / SCSS背景图像循环与nth-child

时间:2016-08-09 12:02:04

标签: loops sass background-image

我正在创建静态网站的投资组合部分,我想要一种分配背景图片网址的简洁方法,而不添加任何类名(图像图像-1,图像图像-2等)。 )或HTML中的样式标签,,而是仅使用带有nth-child的scss,如果可能的话 ......

因为图像div是嵌套的,所以在使用nth-child分配背景图像时会遇到一些问题。我创建了一个JSFiddle来重现问题(图像div嵌套在行中)。

我的图片文件的名字就像小提琴一样(image-1.jpg,image-2.jpg等)。

小提琴 - > https://jsfiddle.net/szmvfo4o/

循环:

@for $i from 1 through 3 {

  .row:nth-child(#{$i}) {

    .image:first-child {
      background-image: url(image-#{$i}.jpg);
    } 

    .image:last-child {
      background-image: url(image-#{$i+1}.jpg);
    } 

  }

}

完整的SCSS:

.item {

  float: left;
  width: 50%;
  height: 120px;
  padding: 10px;
  box-sizing: border-box;

}

.inner {

  width: 100%;
  height: 100%;

}

.image {

  width: 100%;
  height: 100%;
  background-size: cover;
  background-color: #fff;
  //background-image: url(https://source.unsplash.com/-sQ4FsomXEs/800x600);
  background-image: url(image-1.jpg);

}

@for $i from 1 through 3 {

  .row:nth-child(#{$i}) {

    .image:first-child {
      background-image: url(image-#{$i}.jpg);
    } 

    .image:last-child {
      background-image: url(image-#{$i+1}.jpg);
    } 

  }

}

HTML:

<div class="row">

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

</div>

<div class="row">

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

</div>

<div class="row">

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

  <div class="item">
    <div class="inner">
      <div class="image"></div>
    </div>
  </div>

</div>

2 个答案:

答案 0 :(得分:0)

你的循环错了。

请使用以下代码。

@for $i from 1 through 3 {

  .row:nth-child(#{$i}) {
    .item:first-child {
      .image {
        background-image: url(image-#{$i}.jpg);
      } 
    }
    .item:last-child {
      .image {
        background-image: url(image-#{$i+1}.jpg);
      } 
    }

  }

}

答案 1 :(得分:0)

你也可以考虑使用flexbox。将所有内容包装在容器div中

.container {
  display: flex;
  flex-wrap: wrap;
}

摆脱行div,不需要行,循环看起来像这样:

@for $i from 1 through 6 {

    .item:nth-child(#{$i}) {
      .inner {
        .image {
          background-image: url(image-#{$i}.jpg);
          }
      }
    } 
}

请参阅此处小提琴中的其余代码&gt;&gt; https://jsfiddle.net/2f0hgfh8/

在之前的解决方案中,循环没有正常工作,因为在每一行($ i)它计算图像$ i和$ i + 1。结果它看起来像这样:

image1 image2
image2 image3
image3 image4
image4 image5