Menu
Coddy logo textTech

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 icon

Challenge

Easy

You've been tasked with styling a simple HTML form using attribute selectors.

Apply the following styles using attribute selectors:

  1. Add a green border to input fields with the attribute type set to "text".
  2. Change the background color of input fields with the attribute type set to "email" to lightblue.
  3. Make the text color of input fields with the attribute type set 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