如何使用 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