2016-08-09 15 views
0

静的なウェブサイトのポートフォリオセクションを作成しています。クラス名を追加せずにbackground-image url:sを割り当てています。 HTML、で、画像等の画像-2)、またはスタイルのタグではなく、画像のdivが入れ子になっているので、私が使用して背景画像を割り当てるいくつかの問題を抱えている ...SASS/SCSS nth-childを使用した背景画像のループ

可能な場合は、n番目の子を持つ唯一のSCSSを使用n番目の子供。私は問題を再現するために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> 

答えて

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); 
     } 
    } 

    } 

} 
0

フレックスボックスの使用を検討することもできます。行の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); 
      } 
     } 
    } 
} 

は、ここではフィドルのコードの残りの部分を見る>>https://jsfiddle.net/2f0hgfh8/

すべての行($ i)でイメージ$ iおよび$ i + 1がカウントされたため、以前のソリューションではループは正しく機能しませんでした。結果は次のようになります。

image1 image2 
image2 image3 
image3 image4 
image4 image5