Presence and Exact Values
Lesson 12 of 15 in Coddy's CSS Selectors course.
In this lesson, you will learn about attribute presence and exact value selectors. Attribute selectors are used to select elements based on the presence or absence of an attribute, or the exact value of an attribute.
Attribute Presence Selector:
The attribute presence selector targets elements that have a specific attribute, regardless of its value. It's denoted by using square brackets with the attribute name inside.
Example:
/* Selects all elements with a "target" attribute */
[target] {
color: blue;
}Exact Value Selector:
The exact value selector targets elements with a specific attribute and a specific attribute value. It's denoted by using square brackets with the attribute name followed by an equal sign and the desired value inside.
Example:
/* Selects the element with "data-type" attribute having the value "important" */
[data-type="important"] {
font-weight: bold;
}Code Examples:
HTML:
<p>This is a <span target="link">link</span> element.</p>
<p data-type="important">This is an important paragraph.</p>CSS:
[target] {
text-decoration: underline;
}
[data-type="important"] {
color: red;
}These examples demonstrate how CSS attribute selectors work by selecting elements based on the presence or exact value of their attributes and applying corresponding styles to them.
Challenge
EasyYou've been tasked with styling a simple HTML form using attribute selectors.
Apply the following styles using attribute selectors:
- Add a
greenborder to input fields with the attributetypeset to "text". - Change the background color of input fields with the attribute
typeset to "email" tolightblue. - Make the text color of input fields with the attribute
typeset to "password"red.
Try it yourself
<!DOCTYPE html>
<html>
<head>
<title>Styled Form</title>
<style>
/* Apply styles to form fields based on attribute values */
</style>
</head>
<body>
<form>
<label for="name">Name:</label>
<input type="text" name="name" id="name">
<label for="email">Email:</label>
<input type="email" name="email" id="email">
<label for="password">Password:</label>
<input type="password" name="password" id="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
All lessons in CSS Selectors
4Attribute selectors
Intro to Attribute SelectorsPresence and Exact ValuesAttribute Value selectors Attribute Value selectors IIAttribute Value selectors III3Combinator Selectors
Child selectorDescendant selectorAdjacent sibling selectorGeneral sibling selector