Chrome/Safari: box-shadow only appears on text inp

2019-03-14 18:51发布

问题:

I'm running into a problem with WebKit browsers (Chrome 15.0.x and Safari 5.1.1) where box shadows are not being rendered on text inputs. Just by chance, I discovered that explicitly setting the border causes the box shadow to render, even if you set the border to 'none' or the default, 'inset'. The code below (view it in action on JSFiddle) demonstrated the problem when viewed with Chrome or Safari, but it renders as expected in Firefox 6.0.2 and Opera 11.52.

HTML

<input type="text" value="Works" style="border:none;" />
<input type="text" value="Works" style="border:inset;" />
<input type="text" value="Doesn't" />

CSS

input[type="text"] {
    margin: 1em;

    -webkit-box-shadow: 0px 0px 2px 1px green;
    box-shadow: 0px 0px 2px 1px green;
}

Am I missing some detail of using box shadows in WebKit or have I found a bug?

回答1:

inputs, in WebKit, have this property applied to them by default:

-webkit-appearance: textfield;

This is what you want if you want the appearance of the text field to be platform-dependent. Sometimes you can style it with this still set, but other times, it needs to be set to none, which makes it apply standard CSS and rely less on the operating system. It seems border automatically triggers this, but box-shadow does not, yet box-shadow is only applied if -webkit-appearance is none. (the fact that the platform-dependent appearance is not turned off if box-shadow is applied and that box-shadow is not rendered if the platform-dependent appearance is enabled may be a bug)

To fix this, simply explicitly tell it to not use the platform-dependent appearance:

input[type="text"] {
    -webkit-appearance: none;
}

Test it with -webkit-appearance: none; added.

The downside of this is you lose (some of) the platform's native look, but if you're trying to use box-shadow, you might be trying to style away the native look anyways.