提取正文类以在 Scss 中使用 [英] Extract body class for use in Scss

查看:24
本文介绍了提取正文类以在 Scss 中使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习 Sass,但在尝试解决问题时有点卡住了.我想在不同的页面上有一个独特的背景图片和标题图片.我怎样才能从标记中提取主体类名称并在 scss 中解释它?

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 body class name form the markup and interpret that in scss?

基本上我需要一些方法来防止不得不这样做(这完全是 scss 的重点?!)

Essentially I require some way to prevent having to do this (which is totally the point of scss right?!)

body.page1 {
  background: url(../img/bkg-page1.png) left top repeat-x;

  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;

  header {
    background: url(../img/header-page2.png) center top no-repeat;
    height: 320px; 
  }

}

我意识到使用变量是正确的方向,但不确定如何将标记类中继到 scss.

I realise using variables is the right direction, but not sure how to relay the markup class to the scss.

任何指针将不胜感激.

推荐答案

您正在寻找的是 @each 循环:

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

如果您的类名总是在其名称末尾有数字,您可以改用 @for 循环(这样就不需要类名列表).

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.

这篇关于提取正文类以在 Scss 中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆