CSS - Add Color with a data attribute - attr(data-color color)

前端 未结 6 1119
[愿得一人]
[愿得一人] 2020-12-14 08:16

I\'m trying to add color to different element with a data attribute in my css but doensn\'t work ...

I follow this instructions :

The attr() Function: Proper

相关标签:
6条回答
  • 2020-12-14 08:36

    If you are talking only about colors, you can use currentColor value as a proxy.

    For example:

    HTML

    <td>
       <span class="bgborder" style="color: #e7663f"></span>
       <i class="fa fa-copy"></i>
    </td>
    

    CSS

    .bgborder {
      background-color: currentColor;
    }
    
    0 讨论(0)
  • 2020-12-14 08:36

    alternately a very handy bit of javascript:

    <P _my_colour="red" >one</P>
    <P _my_colour="blue">two</P>
    <P _my_colour="green">three</P>
    <script>
        var my_col = document.querySelectorAll("[_my_colour]");
          my_col.forEach(element => {
            element.style.color = element.getAttribute("_my_colour");
        })
    
    </script>
    

    The css solutions outlined by other contributors are generally better and simpler, so a JS solution is somewhat reinventing the wheel, but does do explicitly what you want in the question, so it's here for completeness.

    0 讨论(0)
  • 2020-12-14 08:37

    I guess that you are looking is CSS variables and you can use at Chrome, Firefox and Safari. Check the browser support at Can I use

    And can see more at the video from Lea Verou

    0 讨论(0)
  • 2020-12-14 08:48

    Always a good idea to read the documentation: https://developer.mozilla.org/en/docs/Web/CSS/attr

    screenshot of support table

    Surprise! If nothing supports it, then it won't work ;)

    Alternative: If you know you only have a limited range of colours, try:

    [data-color=red] {background-color:red !important}
    [data-color=blue] {background-color:blue !important}
    [data-color=zophan-blue] {background-color:#33ccff !important}
    

    As you can see, this allows flexibility, such as defining your own colours ;)

    0 讨论(0)
  • 2020-12-14 08:49

    Currently, the CSS attr function can only be used with the content property in browsers

    See here for compatibility

    Per the CSS2 spec:

    Limited to the content property

    CSS3 will extend this (proposal)

    ..can be used on all properties; may return other values than <string>

    0 讨论(0)
  • 2020-12-14 08:52

    You can pass css values from html:

    <button style="
        --tooltip-string: 'Ug. Tooltips.';
        --tooltip-color: #f06d06;
        --tooltip-font-size: 11px;
        --tooltip-top: -10px">
      Button
    </button>
    

    to css:

    button::after {
      content: var(--tooltip-string);
      color: var(--tooltip-color);
      font-size: var(--tooltip-font-size);
    }
    

    source: https://css-tricks.com/css-attr-function-got-nothin-custom-properties/ codepen: https://codepen.io/chriscoyier/pen/EbxVME

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