使用 CSS 属性选择器为表单设置样式
使用 CSS 中的属性选择器,为具有特定属性的 HTML 元素应用样式。让我们看看哪些属性选择器可用于规则。
[attribute] 选择器
[attribute] 选择器选择具有指定属性的元素。这里,带有 target 属性的链接将被设置样式 -
a[target] {
background-color: red;
color: white;
}
示例
让我们看看这个例子 -
<!DOCTYPE html>
<html>
<head>
<style>
a[target] {
background-color: red;
color: white;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<a href="https://tutorialspoint.com" target="_blank">Tutorialspoint</a>
<a href="http://www.tutorix.com">Tutorix</a>
</body>
</html>
[attribute="value"] 选择器
[attribute="value"] 选择器选择具有指定属性和值的元素。这里,属性是 target,值是 _blank。具有此 target 属性和 _blank 值的 <a> 将被设置样式 -
a[target="_blank"] {
background-color: red;
color: white;
}
示例
让我们看看这个例子 -
<!DOCTYPE html>
<html>
<head>
<style>
a[target="_blank"] {
background-color: red;
color: white;
}
</style>
</head>
<body>
<h2>Demo Heading</h2>
<a href="https://tutorialspoint.com" target="_blank">Tutorialspoint</a>
<a href="http://www.tutorix.com" target="_self">Tutorix</a>
</body>
</html>
属性选择器应用了以下规则。
p[lang] - 选择所有具有 lang 属性的段落元素。
p[lang="fr"] - 选择 lang 属性值正好为“fr”的所有段落元素。
p[lang~="fr"] - 选择 lang 属性包含单词“fr”的所有段落元素。
p[lang|="en"] - 选择 lang 属性值正好为“en”或以“en-”开头的所有段落元素。
在下面的示例中,我们使用属性选择器为表单设置了样式。让我们看看它是如何实现的 -
设置 input 类型为 text 的样式
这里,我们使用 CSS [attribute] 选择器为 input 类型为 text 的元素设置了样式。以下样式仅针对类型为 text 的 input 元素设置 -
input[type="text"] {
width: 300px;
display: block;
margin-bottom: 10px;
background-color: rgb(195, 250, 247);
font-size: 18px;
padding: 15px;
border: none;
}
设置 input 类型为 password 的样式
这里,我们使用 CSS [attribute] 选择器为 input 类型为 password 的元素设置了样式。以下样式仅针对类型为 password 的 input 元素设置 -
input[type="password"] {
width: 300px;
padding: 10px;
background-color: red;
color: white;
border: none;
}
设置 input 类型为 button 的样式
这里,我们使用 CSS [attribute] 选择器为 input 类型为 button 的元素设置了样式。以下样式仅针对类型为 button 的 input 元素设置 -
input[type="button"] {
padding: 10px;
font-size: 18px;
border: none;
outline: none;
background-color: rgb(75, 163, 16);
color: white;
}
示例
以下是代码 -
<!DOCTYPE html>
<html>
<head>
<style>
body {
font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
}
input[type="text"] {
width: 300px;
display: block;
margin-bottom: 10px;
background-color: rgb(195, 250, 247);
font-size: 18px;
padding: 15px;
border: none;
}
input[type="button"] {
padding: 10px;
font-size: 18px;
border: none;
outline: none;
background-color: rgb(75, 163, 16);
color: white;
}
input[type="password"] {
width: 300px;
padding: 10px;
background-color: red;
color: white;
border: none;
}
</style>
</head>
<body>
<h1>Css attribute selector example</h1>
<form>
<label for="fname">First name:</label><br />
<input type="text" id="fname" name="fname" value="Ron" />
<label for="lname">Last name:</label><br />
<input type="text" id="lname" name="lname" value="Shaw" />
<label for="pass">Password:</label><br />
<input type="password" id="pass" name="pass" value="password" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP