Extract body class for use in Scss

后端 未结 1 660
生来不讨喜
生来不讨喜 2021-01-27 06:50

I am learning Sass but a bit stuck trying to work something out. I\'d like to have a unique background image and header image on different pages. How can I perhaps extract the b

相关标签:
1条回答
  • 2021-01-27 07:50

    What you're looking for is an @each loop:

    @each $class in (page1, page2, page3) {
        body.#{$class} {
            background: url(../img/bkg-#{$class}.png) left top repeat-x;
    
            header {
                background: url(../img/header-#{$class}.png) center top no-repeat;
                height: 320px; 
            }
        }
    }
    

    This assumes that the class name corresponds to the image name, as indicated in your sample.

    body.page1 {
      background: url(../img/bkg-page1.png) left top repeat-x;
    }
    
    body.page1 header {
      background: url(../img/header-page1.png) center top no-repeat;
      height: 320px;
    }
    
    body.page2 {
      background: url(../img/bkg-page2.png) left top repeat-x;
    }
    
    body.page2 header {
      background: url(../img/header-page2.png) center top no-repeat;
      height: 320px;
    }
    
    body.page3 {
      background: url(../img/bkg-page3.png) left top repeat-x;
    }
    
    body.page3 header {
      background: url(../img/header-page3.png) center top no-repeat;
      height: 320px;
    }
    

    You could use a @for loop instead (which eliminates the need for the list of class names) if your class names are always going to have numbers at the end of their name.

    0 讨论(0)
提交回复
热议问题