如何使用 CSS 更改文字框佔位符的顏色?
使用::placeholder偽元素,我們可以更改文字框的佔位符文字顏色。此外,還可以使用:last-child偽類選擇表單輸入。
語法
CSS ::placeholder 偽元素的語法如下:
::placeholder {
attribute: /*value*/
}
預設佔位符
示例
讓我們首先看看預設的佔位符顏色是什麼樣的:
<!DOCTYPE html>
<html>
<body>
<h1>Fill the form</h1>
<form>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Enter your firstname">
</form>
</body>
</html>
具有不同顏色的佔位符
現在,我們將瞭解如何建立顏色與預設值不同的佔位符:
建立表單並設定輸入欄位
首先,使用<form>建立一個表單,並使用placeholder屬性設定輸入型別:
<form> <label for="fname">First Name</label> <input type="text" id="fname" name="firstname" placeholder="Enter your firstname"> <label for="lname">Last Name</label> <input type="text" id="lname" name="lastname" placeholder="Enter your surname"> </form>
上面,我們還設定了佔位符:
placeholder="Enter your firstname" placeholder="Enter your surname"
設定佔位符顏色
要設定佔位符的顏色,請使用color屬性,但使用::placeholder偽元素設定它:
<style>
input:last-child::placeholder {
color: cornflowerblue;
}
</style>
示例
現在讓我們看看使用 CSS ::placeholder 偽元素的示例:
<!DOCTYPE html>
<html>
<head>
<style>
input:last-child::placeholder {
color: cornflowerblue;
}
</style>
</head>
<body>
<h1>Fill the form</h1>
<form>
<label for="fname">First Name</label>
<input type="text" id="fname" name="firstname" placeholder="Enter your firstname">
</form>
</body>
</html>
使用 Flex 對齊輸入欄位並設定佔位符
我們現在將設定輸入型別並使用 flex 對其進行排列。還將為輸入欄位設定佔位符。預設顏色已更改,使用與 ::placeholder 一起設定的 color 屬性更改:
<!DOCTYPE html>
<html>
<head>
<style>
input::placeholder {
color: fuchsia;
}
input {
margin: 2%;
width: 100%;
}
div {
display: flex;
flex-direction: column;
margin: 3%;
padding: 3%;
text-align: center;
align-items: center;
box-shadow: inset 0 0 30px brown;
}
button {
width: 40%;
}
</style>
</head>
<body>
<div>
<input type="text" placeholder="Normal placeholder" />
<input type="email" placeholder="somenone@somewhere.com" />
<button>dummy btn</button>
</div>
</body>
</html>
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP