CSS如何修改placeholder樣式

項目用常常遇到修改input的placeholder的顏色的需求,這裏來看一下placeholder如何用css設置:css

原文發佈與個人我的博客>>html

首先來看一下chrome默認的input樣式web

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

(placeholder)chrome

c591ae0a-06d2-4f06-afcc-c1948ab7bded

(input style)瀏覽器

9fdc4846-3525-4577-85de-fb6398f2ec76

能夠發現,placeholderinput的默認顏色是有點區別的。如今咱們來修改input 的顏色post

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

(placeholder)spa

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

(input)3d

fb3e8298-bfee-480b-bf14-192c85f6f524

不難發現color屬性只能改變輸入值的顏色,placeholder的顏色沒人任何變化。so,如何來改變placeholder的顏色。code

要改變placeholder的顏色就要使用到僞類::placeholderhtm

<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;
}
相關文章
相關標籤/搜索