css样式中&的用法

2023-12-27  本文已影响0人  竖起大拇指

一、认识“&”

在css中,“&”符号通常用于选择器中,表示选择某个元素的子元素或特定状态下的元素.

二、“&”的用法

1、&- :连接父元素和子元素的类名
用法:

.btn {
  &-primary {
    background-color: #007bff;
    color: #fff;
  }
}

编译出来的结果是在btn后面拼接了类名:

.btn-primary {  
   background-color: #007bff;
   color: #fff;
}

2、&. :连接父元素和子元素的类名
用法:

.btn {
  &.primary {
    background-color: #007bff;
    color: #fff;
  }
}

编译出来的结果是同一个元素,有两个类名,两个类名之间没有空格:

.btn.primary {
   background-color: #007bff;
   color: #fff;
}

3、&::before和&::after :表示在当前元素的前面或后面插入伪元素

btn {
  &::before {
    content: "before";
  }
  
  &::after {
    content: "after";
  }
}

4、&:hover&:focus:表示鼠标悬停聚焦时应用的样式

btn {
  &:hover {
    background-color: #eee;
  }
  
  &:focus {
    outline: none;
    box-shadow: 0 0 0 2px #007bff;
  }

编译后的结果是当用户悬停在 button 元素上时,应用 background-color: #eee; 样式;当用户聚焦在 button 元素上时,应用 outline: none; box-shadow: 0 0 0 2px #007bff; 样式。

5、&[attribute=value] :表示选择具有特定属性和属性值的元素
用法:

btn {
  &[disabled] {
    opacity: 0.5;
    cursor: not-allowed;
  }
  
  &[type="submit"] {
    background-color: #007bff;
    color: #fff;
  }
}

编译出来的结果是选择具有 disabled 属性的 button 元素,并应用 opacity: 0.5; cursor: not-allowed; 样式;同时选择具有 type="submit" 属性的 button 元素,并应用 background-color: #007bff; color: #fff; 样式:

button[disabled] {
  opacity: 0.5;
  cursor: not-allowed;
}
 
button[type="submit"] {
  background-color: #007bff;
  color: #fff;
}

6、&:nth-child(n)&:nth-of-type(n):表示选择特定位置的子元素或同类型元素

ul {
  li {
    &:nth-child(odd) {
      background-color: #f7f7f7;
    }
    
    &:nth-of-type(even) {
      color: #007bff;
    }
  }
}

7、&:first-child 选择器用来匹配父元素中第一个子元素。
&:last-child 选择器用来匹配父元素中最后一个子元素。

上一篇 下一篇

猜你喜欢

热点阅读