代码之家  ›  专栏  ›  技术社区  ›  Andrew Foulds

CSS通用选择器不适用于SVG

  •  0
  • Andrew Foulds  · 技术社区  · 2 年前

    如果我有这个HTML

    <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
      <g id="repeat">
        <path fill="currentColor"
          d="M20.3 13.43a1 1 0 0 0-1.25.65A7.14 7.14 0 0 1 12.18 19A7.1 7.1 0 0 1 5 12a7.1 7.1 0 0 1 7.18-7a7.26 7.26 0 0 1 4.65 1.67l-2.17-.36a1 1 0 0 0-1.15.83a1 1 0 0 0 .83 1.15l4.24.7h.17a1 1 0 0 0 .34-.06a.33.33 0 0 0 .1-.06a.78.78 0 0 0 .2-.11l.09-.11c0-.05.09-.09.13-.15s0-.1.05-.14a1.34 1.34 0 0 0 .07-.18l.75-4a1 1 0 0 0-2-.38l-.27 1.45A9.21 9.21 0 0 0 12.18 3A9.1 9.1 0 0 0 3 12a9.1 9.1 0 0 0 9.18 9A9.12 9.12 0 0 0 21 14.68a1 1 0 0 0-.7-1.25Z" />
      </g>
    </svg>
    <svg id="btnRepeat" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="button">
      <use href="#repeat"></use>
    </svg>
    

    和这个CSS

    :root {
      --norm-colour: green;
      --high-colour: red;
    }
    
    #btnRepeat {
      position: absolute;
      width: 15%;
      color: var(--norm-colour);
    }
    
    #btnRepeat:hover {
      color: var(--high-colour);
      cursor: pointer;
    }
    

    svg的颜色是正确的,并在悬停时按预期变化。

    如果我将选择器从 #bt重复:悬停 的“通用”形式 svg[id^=“btn”]:悬停 悬停时不会发生颜色变化(尽管光标发生了变化。)为什么通用表单失败了?

    1 回复  |  直到 2 年前
        1
  •  1
  •   Shuo    2 年前

    因为id选择器具有更高的优先级。

    :root {
      --norm-colour: green;
      --high-colour: red;
    }
    
    [id^="btn"] {
      position: absolute;
      width: 15%;
      color: var(--norm-colour);
    }
    
    [id^="btn"]:hover {
      color: var(--high-colour);
      cursor: pointer;
    }
    <svg xmlns="http://www.w3.org/2000/svg" style="display: none;">
            <g id="repeat">
                <path fill="currentColor" d="M20.3 13.43a1 1 0 0 0-1.25.65A7.14 7.14 0 0 1 12.18 19A7.1 7.1 0 0 1 5 12a7.1 7.1 0 0 1 7.18-7a7.26 7.26 0 0 1 4.65 1.67l-2.17-.36a1 1 0 0 0-1.15.83a1 1 0 0 0 .83 1.15l4.24.7h.17a1 1 0 0 0 .34-.06a.33.33 0 0 0 .1-.06a.78.78 0 0 0 .2-.11l.09-.11c0-.05.09-.09.13-.15s0-.1.05-.14a1.34 1.34 0 0 0 .07-.18l.75-4a1 1 0 0 0-2-.38l-.27 1.45A9.21 9.21 0 0 0 12.18 3A9.1 9.1 0 0 0 3 12a9.1 9.1 0 0 0 9.18 9A9.12 9.12 0 0 0 21 14.68a1 1 0 0 0-.7-1.25Z" />
            </g>
        </svg>
    <svg id="btnRepeat" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" role="button">
            <use href="#repeat"></use>
        </svg>

    根据MDN文档 How is specificity calculated? :

    选择器 重量
    ( IDs -
    Classes, attributes and pseudo-classes -
    Elements and pseudo-elements )
    #btnRepeat 1-0-0
    [id^="btn"]:hover 0-2-0
    推荐文章