Understanding CSS Attribute and Pseudo-class Selectors
Attribute Selectors
CSS attribute selectors target elements based on matching specific attribute values. The example below demonstrates basic and chained attribute selector usage:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
/* Target all password input fields */
input[type="password"] {
background-color: #ffcccc;
}
/* Match multiple attribute conditions */
input[type="text"][value="demo_user1"] {
background-color: #ffffcc;
}
</style>
</head>
<body>
<form>
Username: <input type="text" value="demo_user1" />
Username 2: <input type="text" value="demo_user2" />
Password: <input type="password" value="********" />
<input type="submit" value="Log In" />
</form>
</body>
</html>
Pseudo-class Selectors
Pseudo-class selectors add state-based special effects to selected elements, only applying styles whenn an element meets a specific interaction or state condition.
Basic hover state example:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.hover-heading:hover {
color: #ff0000;
}
</style>
</head>
<body>
<h1 class="hover-heading">Hover over this heading</h1>
</body>
</html>
Pseudo-class selectors are most commonly used for styling hyperlinks to match different interaction states:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
/* Unvisited link state */
a:link {
color: #ffcc00;
}
/* Mouse hover state */
a:hover {
color: #ff0000;
}
/* Active clicked state */
a:active {
color: #0000ff;
}
/* Visited link state */
a:visited {
color: #009900;
}
</style>
</head>
<body>
<a href="#">Sample Hyperlink</a>
</body>
</html>
Practice: Build a Site Navigation Bar
The example below creates a simplifeid top navigation bar:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<style>
.top-nav {
position: absolute;
right: 200px;
}
.top-nav ul {
list-style-type: none;
}
.top-nav li {
float: left;
margin-left: 20px;
}
.top-nav a {
text-decoration: none;
font-size: 13px;
color: #000000;
}
.top-nav a:hover {
color: #0000FF;
}
</style>
</head>
<body>
<div class="top-nav">
<ul>
<li><a href="#">News</a></li>
<li><a href="#">hao123</a></li>
<li><a href="#">Maps</a></li>
<li><a href="#">Videos</a></li>
</ul>
</div>
</body>
</html>