Scss--嵌套--使用/实例

原文网址:Scss--嵌套--使用/实例_IT利刃出鞘的博客-CSDN博客

简介

        本文用示例介绍Scss的嵌套的用法。

嵌套的用法

说明

        Sass 允许将一套 CSS 样式嵌套进另一套样式中,内层的样式将它外层的选择器作为父选择器。嵌套功能避免了重复输入父选择器,而且令复杂的 CSS 结构更易于管理。

示例

Scss:

#main p {
  color: #00ff00;
  width: 97%;

  .redbox {
    background-color: #ff0000;
    color: #000000;
  }
}

编译后的CSS:

#main p {
  color: #00ff00;
  width: 97%;
}

#main p .redbox {
  background-color: #ff0000;
  color: #000000;
}

父选择器

        在嵌套 CSS 规则时,有时需要使用嵌套外层的父选择器。例如,当给某个元素设定 hover 样式时,或者当 body 元素有某个 classname 时,可以用 & 代表嵌套规则外层的父选择器。

简单示例

Scss:

a {
  font-weight: bold;
  text-decoration: none;
  &:hover {
    text-decoration: underline;
  }
  body.firefox & {
    font-weight: normal;
  }
}

编译后的CSS:

a {
  font-weight: bold;
  text-decoration: none;
}

a:hover {
  text-decoration: underline;
}

body.firefox a {
  font-weight: normal;
}

嵌套是可传递的

        编译后的 CSS 文件中 & 将被替换成嵌套外层的父选择器,如果含有多层嵌套,最外层的父选择器会一层一层向下传递:

Scss:

#main {
  color: black;
  a {
    font-weight: bold;
    &:hover {
      color: red;
    }
  }
}

编译后的CSS:

#main {
  color: black;
}

#main a {
  font-weight: bold;
}

#main a:hover {
  color: red;
}

&后可以跟后缀

说明

        & 必须作为选择器的第一个字符,其后可以跟随后缀生成复合的选择器。

示例

Scss:

#main {
  color: black;
  &-sidebar {
    border: 1px solid;
  }
}

编译后的CSS:

#main {
  color: black;
}

#main-sidebar {
  border: 1px solid;
}

属性嵌套

说明

        有些 CSS 属性遵循相同的命名空间 (namespace),比如 font-family, font-size, font-weight 都以 font 作为属性的命名空间。为了便于管理这样的属性,同时也为了避免了重复输入,Sass 允许将属性嵌套在命名空间中。

简单示例

Scss:

.funky {
  font: {
    family: fantasy;
    size: 30em;
    weight: bold;
  }
}

编译后的CSS:

.funky {
  font-family: fantasy;
  font-size: 30em;
  font-weight: bold;
}

命名空间的属性值

说明

        命名空间也可以包含自己的属性值。

示例

Scss:

.funky {
  font: 20px/24px {
    family: fantasy;
    weight: bold;
  }
}

编译后的CSS:

.funky {
  font: 20px/24px;
  font-family: fantasy;
  font-weight: bold;
}

猜你喜欢

转载自blog.csdn.net/feiying0canglang/article/details/125625234
今日推荐