DEV Community

Cover image for [attribute="value"] vs [attribute*="value"]! Know the difference
FrontEndLord
FrontEndLord

Posted on

[attribute="value"] vs [attribute*="value"]! Know the difference

When working with CSS, you often need to select and style elements based on their attributes. Two common selectors for attribute selection that we all use are [attribute="value"] **and **attribute.value. While they may seem similar at first, they have distinct differences in functionality and use cases. In this article, I will explore these differences and help you understand when to use each selector.

'[attribute="value"]' Selector

This attribute selector is the specific of the pair. It only allows you to target elements with a specific attribute value. It is so specific that matches elements where the attribute's value is an exact match to the specified value.

Let me show you what I mean by this:

<input type="text" name="name" placeholder="Enter your Full names">
<input type="email" name="email" placeholder="Enter your email">

Enter fullscreen mode Exit fullscreen mode
input[type="text"] {
  /* Styles will only be applied to input elements with type="text" */
/* type="email" will not be affected by this selection */
}

Enter fullscreen mode Exit fullscreen mode

In the above code, the CSS selector input[type="text"] only selects the element with type="text" only. This selector is precise and targets only elements with the exact attribute value of "text". It provides a way to apply specific styles to elements based on their attribute values.

'[attribute*="value"]' Selector

Think of this selector like the laid back parent between the two, it is the mom - or the dad if your mom is an African mom. It is so laid back that it targets elements based on the presence of a specified attribute, regardless of its value.

It does not consider the attribute value but focuses on the attribute's existence itself. Let me show you what I mean:

<input id="registration 1" type="text" name="name" placeholder="Enter your Full names">
<input id="registration 2" type="email" name="email" placeholder="Enter your email">
Enter fullscreen mode Exit fullscreen mode
[id*=1]{
/* Although they both have the same id of registration, .2 will not be selected*/
/*If any styles will be applied, .2 will be left untouched*/
}
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, I am open to criticism.

Top comments (0)