How to Target Elements in CSS with Attributes

| Web Design
How to Target Elements in CSS with Attributes

When working with CSS, designers usually target elements based on id or class. However you can target elements using more than just these two attributes.

There are many instances when you want to target an element but avoiding the two most common CSS selectors.

In this post we will show you how to target elements in CSS with attributes beyond id and class. 

Target an element with an attribute and its exact value

In our first example, we want to target this text box with CSS:

<input type="text" name="myfield">

We can use the attribute type as part of the selector. The CSS selector will look like this:

input[type="text"] {
 /* Your custom CSS goes here */
}

We can also use the attribute name as selector. The key is to put the attribute and its exact value within brackets next to the tag name:

input[name="myfield"] {
 /* Your custom CSS goes here */
}

Target elements with the same attribute and similar values

In our second example, we may have several elements sharing the same attribute but not exactly the same values.

<input type="text" name="myfield1">
<input type="text" name="yourfield1">
<input type="text" name="myfield2">
<input type="text" name="yourfield2">

Let’s target the fields with the attribute name only when the value includes yourfield:

input[name*="yourfield"] {
 /* Your custom CSS goes here */
}

The code looks very similar to the previous example, however note we added the asterisk symbol (*) to target all the elements whose name value includes the string yourfield. The end result is that the elements yourfield1 and yourfield2 are targeted.


About the author

Valentín creates beautiful designs from amongst the tequila plants of Jalisco, Mexico. You can see Valentín's design work all over this site and you can often find him helping members in support.