简体   繁体   中英

How to implement immediate parent selector in SASS, SCSS?

I have HTML layout as below:

<div class="card">
    <div class="section">
        <div class="item"></div>
        <div class="item"></div>
        <div class="item"></div>    
    </div>
</div>

Compiled CSS should look like:

.card{
}

.card .section .item{
}

.card .section .item+.item{
}

What I'm writing in SCSS:

.card{

    .section{

        .item{

            &+&{
            }
        }
    }
}

Can we have something like & + & , which is not working, I do not want to write,

.card{

    .section{

        .item{
        }
        .item+.item{
        }
    }
}

& is the parent selector, you can't use two & because then you'd be out of the scope. In that case, just go up one block.

Ex:

#main {
  color: black;
  a {
    font-weight: bold;
    &:hover { color: red; } /* Look at notes below */
  }
}

Compiles to

#main {
  color: black; }
  #main a {
    font-weight: bold; }
    #main a:hover { /* parent selector is replaced :D  */
      color: red; }

If you used two & adjacently you would be in the parent of the parent, which wouldn't make sense since you can just write your sass or scss one code block higher in the hierarchy.

DOCUMENTATION: Referencing Parent Selectors: &

The following scss did the trick:

.card{

    .section{

        .item{

            &+.item{
            }
        }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM