What is the reason for an attribute selector having greater specificity compared to a class selector?

Why is it that the input[type=number] selector in the following example takes precedence over the .num class selector? Shouldn't they both have equal specificity?

I assumed that the one declared later would overwrite the earlier one.

input {
  width: 100px;
}

input[type=number] {
  border: 2px solid green;
}

.num {
  border: 2px solid red;
}
<input type="number" class="num"> Why isn't the border red (as specified by .num)?

Answer №1

In the realm of specificity, attribute selectors are on par with CSS class selectors. Take for instance your use of input[type=number] and .num.

  • The specificity of input[type=number] is 0 0 1 1, encompassing an element input and an attribute [type=number].
  • On the other hand, .num holds a specificity of 0 0 1 0 with only a class selector.

Given that input[type=number] boasts higher specificity than .num, its style will prevail regardless of order. However, if input[type=number] were altered to [type=number], their equality in specificity at 0 0 1 0 would allow placement to determine the victor.

input {
  padding: 0.25em 0.5em;
}

/* Specificity - 0, 0, 1, 1 */
input[type="number"] {
  border-style: dotted;
}

/* Specificity - 0, 0, 1, 0 */
[type="number"] {
  border: 1px dashed indianred;
}

/* Specificity - 0, 0, 1, 0 */
.num {
  border-color: rebeccapurple;
}

/* Specificity - 0, 0, 1, 0 */
[type="number"] {
  border-style: solid;
  border-width: 2px;
}
<input type="number" class="num" name="number" value="0">

* A repetition of the same CSS selector was utilized purely for illustrative reasons. Notice which border-style takes precedence. Despite attempts to switch from dotted to dashed or solid, neither overruled due to specificity. In such cases, the ordering of rules comes into play when specificity values match.

Answer №2

What is the reason for an attribute selector having a higher specificity compared to a class selector?

It is a common misconception that attribute selectors have higher specificity than class selectors, when in fact both have a specificity of 0,0,1,0.

In the provided example, why does the input[type=number] selector take precedence over the .num class selector? Shouldn't they both have a specificity of 1?

The combination of a type selector (input) and an attribute selector ([type=number]) results in a specificity of 0,0,1,1, giving it a higher priority over the class selector.

Answer №3

To grasp the essence of specificity, it's essential to comprehend the specific order of the 3 column specificity hierarchy

  1. Inline styles (which hold higher priority than the following three, although not technically part of the 3 column specificity)
  2. ID selectors (examples: #example)
  3. Class selectors (includes classes, attributes, and pseudo-classes. examples: .myClass, [type="radio"], :hover)
  4. Type selectors (encompassing elements and pseudo-elements. examples: p, h1, ::before)

!important rule exception: When a style carries the !important flag, its significance prevails regardless of specificity levels

In a given instance, the attribute selector input[type='number'] holds greater specificity compared to the class selector .num. Let's analyze the specificity of each selector:

Element with Attribute Selector input[type='number']:

Specificity: 0, 1, 1 (one attribute selector, one element selector)

Class Selector .num:

Specificity: 0, 1, 0 (one class selector)

Although both selectors possess a specificity value of 1 in the second column (representing classes, attributes, or pseudo-classes), the attribute selector additionally includes the Type selector specificity of 1, elevating its specificity level. Consequently, the styling specified by input[type='number'] will take precedence over the styling attributed to the class selector .num.

For further insights into understanding specificity, here's an informative article: link

Answer №4

Essentially, the reason lies in the fact that your CSS is tailored more precisely for that particular type of input element.

A rule targeting input or .num or [type="input"] involves only one selector, whereas input[type=number] combines two different selectors.

(Credit to @rozsazoltan.)

Answer №5

Attribute selectors and CSS class selectors have equal specificity levels.

The specificity depends on whether the Attribute Selector and Class Selector are associated with an Element Selector or not.

For example:

Attribute Selector [data-foo="underline"] Specificity: [0, 1, 0]

Class Selector .underline Specificity: [0, 1, 0]

Attribute Selector (With Element Selector)

u[data-foo="underline"]
Specificity: [0, 2, 0]

Class Selector (With Element Selector) u.underline Specificity: [0, 2, 0]

In essence, an Attribute Selector without an Element Selector will have the same specificity as a Class Selector without an Element Selector.

An Attribute Selector with an Element Selector will have the same specificity as a Class Selector with an Element Selector.

However, if either selector is associated with an Element Selector, their specificities will differ.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Choose from the options provided to display the table on the screen

One of the challenges I am facing involves a table with two columns and a select option dropdown box. Each row in the table is associated with a color - green indicates good, red indicates bad, and so on. My goal is to have all values displayed when the pa ...

Include a remove button in PHP/HTML

I'm working with the code below to fetch rows from a database where the username column matches the base directory name: $username = basename(dirname(__FILE__)); $username = mysql_real_escape_string($username); $result = mysql_query("SELECT link, no ...

What is the best way to maintain an input String when refreshing a page using Selenium Webdriver?

When using Selenium webdriver, I am facing an issue where the value in an input element is not retained after refreshing the page. Interestingly, when testing manually, the scenario works as expected. Is there a way to ensure that the input string remain ...

The issue with Bootstrap 4 fixed-top not functioning properly on mobile devices

An issue has arisen while using 'fixed-top' with Bootstrap 4. This feature works perfectly fine on the desktop for my nav bar, but when the navbar is collapsed, it fails to fix itself at the absolute top. Instead, when scrolling in the collapsed ...

Listening to a variety of MP3 files

Last weekend, my dad asked me to transfer a few CDs to his digital library so he can listen to them anywhere. I was thinking of hosting the MP3 files on my server and creating a script that displays all the music files. He could then select one or multiple ...

Seeking a precise placement, must find a CSS-only answer

After spending two days experimenting with different CSS styles like absolute positioning, inline/inline-block display, and flex display, I have yet to find a solution for styling a timestamp's label position using pure CSS. https://i.stack.imgur.com ...

Having trouble getting my initial Vue.js code to function properly alongside basic HTML

I am in need of assistance with this code as it does not seem to be working properly. I am using an external js file named app.js for the Vue JS code in the index.html file. Here is the code from index.html: new vue({ el: '#app', data: { ...

Utilizing Android WebView for Interactivity with HTML Button and JavaScript

Trying to incorporate a simple HTML file with buttons and JavaScript execution in an Android app using a WebView has been a challenge. Although I have successfully loaded the HTML content into the WebView, I am unable to trigger any JavaScript functions by ...

Caution: the argument provided to mysql_fetch_object() is not a legitimate MySQL result resource

Hello there, I am encountering an error when trying to connect and retrieve data from the database. The error message I receive is: Warning: mysql_fetch_object(): supplied argument is not a valid MySQL result resource in /home/content/49/5548763/html/mat ...

Tips for implementing $setValidity with ng-if for the same field in Angular

Hey there, I'm currently facing an issue with using form.form_field.$setValidity on an ng-if tagged field. When testing out the code, I encountered the following error: angular.js:13642 TypeError: Cannot read property '$setValidity' of unde ...

Integrate SVG into the dropdown menu without duplicating the SVG element

I have an SVG of a right arrow: <svg xmlns="http://www.w3.org/2000/svg" height="24px" viewBox="0 0 24 24" width="24px" fill="#000000"> <path d="M0 0h24v24H0V0z" fill="none"/> ...

Apply a different background color to ion-item when it is clicked

Is there a way to change the background color of an ion-item when it is clicked by a user? Any help on how to achieve this would be greatly appreciated. Here's an example code snippet: <ion-item (click)="openDetail(variant)">{{variant.Product ...

Can you confirm the mobile type, please? Using JavaScript to display a div only once based on the mobile type

Is there a correct way to determine the type of mobile device I'm using? Are there alternative methods to check for the mobile type? Take a look at my approach in the code below. How can I test this using a tool? Does anyone have insights on checki ...

Move the text above within the footer using materialize framework

I'm facing an issue with my materialize footer's text disappearing when I set the height to 35px. Whenever I decrease the size of the footer, the text goes off the screen. How can I adjust it so that it stays visible? <footer style="positio ...

Guide on connecting a URL with a generated ID to the <a href> element

I am currently working on building my own portfolio website using Django. The main idea behind this project is to create posts showcasing the websites that I have developed. These posts will be featured on a page titled "Projects," where viewers can click ...

Building a single-page app optimized for mobile viewing with Foundation framework

Currently facing an issue with the scaling of the viewport on certain mobile devices when loading new content via ng-include in our responsive website built on Foundation. The problem arises as the width of the page breaks, leading to horizontal scrolling. ...

Text scrolls - items are shown all at once

I've been experimenting with creating moving/scrolling text. After some trial and error, I've managed to achieve this effect. If you're interested, you can check out the code on CODEPEN. The issue that's currently bothering me is rel ...

Sorry, we couldn't find the page you were looking for. The request method used was GET and the request URL was http://127.0.0.1:

I've previously reported this error without success, so I'm providing more details now. I am new to coding and recently started a Django & Python project, but encountered some issues. Despite three weeks of troubleshooting, the problems persist. ...

jQuery toggle function fails to toggle div element as intended

I am a JavaScript newbie and I am attempting to create a basic hide and show div toggle, but unfortunately, it is not functioning properly. I cannot seem to pinpoint the issue – initially, I set the div's display to none, then when the course-info-t ...

"Return to previous page" feature

I am having difficulty figuring out how to implement the "go back" function for the page. For instance, I have pages A, B, C, and D. The possible switching between pages is as follows: A -> (B <-> C) -> A or D -> (B <-> C) -> D (w ...