代码之家  ›  专栏  ›  技术社区  ›  theJuls

我的id在CSS或SASS中是什么意思?

  •  1
  • theJuls  · 技术社区  · 6 年前

    我继承了一些CSS代码,它利用了 &

    &#my-id {
      // Content and attributes
    }
    

    还有其他的例子,例如:

    &:before {
      // content and attributes
    }
    

    &:hover {
          // content and attributes
        }
    

    那是什么意思?我找不到一个好的方法来表达这一点,所以我找不到任何东西。如果这是复制品,我很抱歉。

    2 回复  |  直到 6 年前
        1
  •  3
  •   Jack    6 年前

    它引用父选择器。

    输入:

    .parent {
        &.child {
            color: red;
        }
    }
    

    输出:

    .parent.child { color: red }
    

    如果你是用BEM格式写CSS的话,这真的很有帮助,比如:

    .block {
        &__element {
    
            width: 100px;
            height: 100px;
    
            &--modifier {
                 width: 200px;
            }
        }
    }
    
    .block__element { width: 100px; height: 100px;}
    .block__element--modifier { width: 200px;}
    
    <div class="block__element"></div>
    <div class="block__element block__element--modifier"></div>
    

    最后,我共享的所有示例都连接了类名,但您也可以将其用作引用,例如:

    .parent {
        & .child {
             color: red;
        }
    }
    
    .parent {
        .child & {
             color: blue;
        }
    }
    
    
    .parent .child { color: red }
    .child .parent { color: blue }
    

    http://lesscss.org/features/#parent-selectors-feature

    https://blog.slaks.net/2013-09-29/less-css-secrets-of-the-ampersand/

    Using the ampersand (SASS parent selector) inside nested selectors

        2
  •  1
  •   cjaro    6 年前

    这是Sass的一个内置功能: https://css-tricks.com/the-sass-ampersand/

    二者都 分为两类:

    .some-class.another-class { }
    

    你想筑巢,Sass的等价物是:

    .some-class {
         &.another-class {}
    }