CSS: Class name selector- name starts with

前端 未结 2 1700
清歌不尽
清歌不尽 2020-12-11 07:19

I have two different type of class names. The first are named color-*. For example:

color-red
color-blue
color-green

I also ha

相关标签:
2条回答
  • 2020-12-11 07:36

    Think about it in another way. Don't change whatever not contain color inside class name. First change all a to what you want:

    a {
        color: yellow;
    }
    
    a:hover {
        color: orange;
    }
    

    then you can overwrite them with:

    a.color-red{...}
    a.color-blue{...}
    a.color-green{...}
    a.hover-color-red{...}
    a.hover-color-blue{...}
    a.hover-color-green{...}
    

    and now you can use it like:

    <a ... class="color-red hover-color-blue">test</a>
    

    Don't make it complicated. It can work perfectly and also in the future you can maintain your styles more easily.

    If you want to use it everywhere just select it like:

    .color-red{...}
    .color-blue{...}
    .color-green{...}
    .hover-color-red{...}
    .hover-color-blue{...}
    .hover-color-green{...}
    

    see the example here:

    a {
      color: gray;
    }
    a:hover {
      color: orange;
    }
    .color-red, .color-red-hover:hover {
      color: red;
    }    
    .color-blue, .color-blue-hover:hover {
       color: blue;
    }
    <a class="color-red color-blue-hover" href="#">Red</a>
    <a class="color-blue color-red-hover" href="#">Blue</a>
    <a href="#">Normal</a>

    0 讨论(0)
  • 2020-12-11 07:43

    The selector you are using *= matches any attribute containing that string.

    Instead, you want ^=, which matches any attribute beginning with that string.

    A combination would work best:

    a[class^='color-'], a[class*=' color-'] { ... }

    See MDN page on CSS attribute selectors and this other SO answer.

    0 讨论(0)
提交回复
热议问题