How to Target Elements in CSS with Attributes

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.

Author

  • Valentin Garcia

    Valentin discovered Joomla in 2010, and since then he has considered it as the best CMS. Valentin has been coding extensions and templates for Joomla for many years and truly enjoys helping people build their own websites with Open Source tools. He lives in San Julián, Jalisco, México.

    View all posts
0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x