Less使用详解(v3.9.0)—嵌套和父选择器&

9,979 阅读2分钟

该系列:

Less(v3.9.0)使用详解——基本使用

Less(v3.9.0)使用详解——变量

Less(v3.9.0)使用详解——嵌套和父选择器&

Less(v3.9.0)使用详解——extend(嵌套)

Less(v3.9.0)使用详解——mixin(混入)

其他待更新...

嵌套

当css选择器存在父子关系时,可以像下面这样书写

#header {
  color: black;
  .navigation {
    font-size: 12px;
  }
  .logo {
    width: 300px;
  }
}

编译为

#header {
  color: black;
}
#header .navigation {
  font-size: 12px;
}
#header .logo {
  width: 300px;
}

当遇到样式表规则比如@media或@supports时,他会冒泡寻找规则

.component {
  width: 300px;
  @media (min-width: 768px) {
    width: 600px;
    @media  (min-resolution: 192dpi) {
      background-image: url(/img/retina2x.png);
    }
  }
  @media (min-width: 1280px) {
    width: 800px;
  }
}

编译成

.component {
  width: 300px;
}
@media (min-width: 768px) {
  .component {
    width: 600px;
  }
}
@media (min-width: 768px) and (min-resolution: 192dpi) {
  .component {
    background-image: url(/img/retina2x.png);
  }
}
@media (min-width: 1280px) {
  .component {
    width: 800px;
  }
}

父选择器

&表示父选择器

a {
  color: blue;
  &:hover {
    color: green;
  }
}

编译为

a {
  color: blue;
}

a:hover {
  color: green;
}

当去掉&会发现编译为

...
a :hover {
  color: green;
}

变成后代选择器了,与我们实际想要的结果不符合

&能实现类似BEM这样的命名规则

.button {
  &-ok {
    background-image: url("ok.png");
  }
  &-cancel {
    background-image: url("cancel.png");
  }

  &-custom {
    background-image: url("custom.png");
  }
}

编译为

.button-ok {
  background-image: url("ok.png");
}
.button-cancel {
  background-image: url("cancel.png");
}
.button-custom {
  background-image: url("custom.png");
}

&能多次使用,注意空格,

.link {
  & + & {
    color: red;
  }

  & & {
    color: green;
  }

  && {
    color: blue;
  }

  &, &ish {
    color: cyan;
  }
}

编译为

.link + .link {
  color: red;
}
.link .link {
  color: green;
}
.link.link {
  color: blue;
}
.link, .linkish {
  color: cyan;
}

注意&表示的所有的父选择器,而不是最近的祖先节点

.grand {
  .parent {
    & > & {
      color: red;
    }

    & & {
      color: green;
    }

    && {
      color: blue;
    }

    &, &ish {
      color: cyan;
    }
  }
}

编译为

.grand .parent > .grand .parent {
  color: red;
}
.grand .parent .grand .parent {
  color: green;
}
.grand .parent.grand .parent {
  color: blue;
}
.grand .parent,
.grand .parentish {
  color: cyan;
}

由于&表示所有父节点,所以可以实现改变选择器顺序

.header {
  .menu {
    border-radius: 5px;
    .no-borderradius & {
      background-image: url('images/button-background.png');
    }
  }
}

编译为

.header .menu {
  border-radius: 5px;
}
.no-borderradius .header .menu {
  background-image: url('images/button-background.png');
}

当父选择器存在同组时,多个&使用成实现所有的分组的组合

p, a, ul, li {
  border-top: 2px dotted #366;
  & + & {
    border-top: 0;
  }
}

编译成16种(4*4)情况

p,
a,
ul,
li {
  border-top: 2px dotted #366;
}
p + p,
p + a,
p + ul,
p + li,
a + p,
a + a,
a + ul,
a + li,
ul + p,
ul + a,
ul + ul,
ul + li,
li + p,
li + a,
li + ul,
li + li {
  border-top: 0;
}