如何修改placeholder样式

2018-08-01
CSS
5619

项目用经常遇到修改input的placeholder的颜色的需求,这里来看一下placeholder如何用css设置。

首先来看一下chrome默认的input样式

<input type="text" placeholder="hello world">

(placeholder)

c591ae0a-06d2-4f06-afcc-c1948ab7bded

(input style)

9fdc4846-3525-4577-85de-fb6398f2ec76

可以发现,placeholderinput的默认颜色是有点区别的。现在我们来修改input 的颜色

<input type="text" placeholder="hello world" style="color: red">

(placeholder)

b79f0fe1-bebe-469e-845f-8210df88a773

(input)

fb3e8298-bfee-480b-bf14-192c85f6f524

不难发现color属性只能改变输入值的颜色,placeholder的颜色没人任何变化。so,如何来改变placeholder的颜色。

要改变placeholder的颜色就要使用到伪类::placeholder

<style>
    input::placeholder {
        color: green;
    }
</style>
<input type="text" placeholder="hello world" style="color: red;">

(placeholder)

b5e9582d-75a9-4b2b-ab95-d45f171a57b8

(input)

f1add868-2d75-4314-b884-b54fa04425f2

需要注意的是::palceholder伪类的兼容性,以上是在chrome浏览器的运行结果,同样的代码在IE11中就成了这样

(placeholder - ie11)

99c9ed01-ae6a-4d64-9848-ecfda20e7388

(input - ie11)

f1add868-2d75-4314-b884-b54fa04425f2

IE解决方案:

首先IE9及以下不支持placeholder。IE10需要用:-ms-input-placeholder,并且属性需要加上!important提高优先级。

<style>
    input:-ms-input-placeholder {
        color: green !important;
    }
</style>
<input type="text" placeholder="hello world" style="color: red;">

(placeholder ie11)

49a81692-f86c-4614-abb0-87914e5c44d2

(input ie11)

b3c1772c-211a-41dd-bcc1-6cf7aeda7f8b

之后给出其他浏览器的适配方案

/* - Chrome ≤56,
   - Safari 5-10.0
   - iOS Safari 4.2-10.2
   - Opera 15-43
   - Opera Mobile >12
   - Android Browser 2.1-4.4.4
   - Samsung Internet
   - UC Browser for Android
   - QQ Browser */
::-webkit-input-placeholder {
    color: #ccc;
    font-weight: 400;
}

/* Firefox 4-18 */
:-moz-placeholder {
    color: #ccc;
    font-weight: 400;
}

/* Firefox 19-50 */
::-moz-placeholder {
    color: #ccc;
    font-weight: 400;
}

/* - Internet Explorer 10–11
   - Internet Explorer Mobile 10-11 */
:-ms-input-placeholder {
    color: #ccc !important;
    font-weight: 400 !important;
}

/* Edge (also supports ::-webkit-input-placeholder) */
::-ms-input-placeholder {
    color: #ccc;
    font-weight: 400;
}

/* CSS Working Draft */
::placeholder {
    color: #ccc;
    font-weight: 400;
}
扫码体验小程序版