How do I make text-shadow and box-shadow use the text color on all browsers?

前端 未结 1 1869
梦如初夏
梦如初夏 2021-01-17 18:45

I\'m trying to create a style for a box with a shadow that\'s the same color as its text. Because I have several boxes, each with a different text color, I\'d like to avoid

相关标签:
1条回答
  • 2021-01-17 19:10

    The behavior described in CSS1 and CSS2 has been extended in Color level 3 with a currentColor keyword value, which basically means "the computed value of color for this element" and can be used anywhere a color value is accepted. As you might expect, this has been retconned into the border-color propdef as its initial value, as seen in the B&B module, here.

    Since almost every browser that supports box-shadow and text-shadow also supports currentColor, you should be able to just specify that as the shadow color:

    text-shadow: 0 0 0.5em currentColor;
    box-shadow: 0 0 0.5em currentColor;
    

    This explicitly instructs the browser to use the same color as the text, and not whatever it was programmed to use otherwise, in a way normalizing the behavior across browsers. Interactive fiddle.

    Unfortunately, for some really stubborn browsers, like certain versions of some WebKit browsers, the problem lies not in the fact that they do not use currentColor, but the fact that they do not implement currentColor with these properties correctly. This means even if you do try to set the color value explicitly, it still won't work, because that's what they already do — they just aren't doing it correctly.

    Specifically, Safari is known to have no support for currentColor whatsoever until version 4, but for reasons I cannot comprehend, Safari 5.x fails to apply the above declarations correctly, despite being able to apply something like background-color: currentColor just fine. I believe this is fixed in Safari 6.x and later, but since 6.x and later apply declarations without the color component correctly anyway, they don't even need this workaround.

    Passing currentColor explicitly does work around a strange bug in Firefox that prevents it from animating to and from text-shadow or box-shadow values without a color component — in the interactive fiddle linked above, if you change either the div:not(:hover) rule or the div:hover rule to remove currentColor from either shadow declaration, that shadow won't animate in Firefox.

    If you absolutely need to support old versions of WebKit browsers, you'll have no choice but to hardcode the desired color. But considering how frequently and rapidly those browsers update themselves anyway, you're probably better off worrying about old versions of IE instead. Note however that IE9 has no trouble supporting box-shadow without the color component, and likewise for IE10 with text-shadow, so IE does not require this workaround at all. Shock and awe.

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