Html

Why are dashes preferred for CSS selectors HTML attributes

19 September 2026 · 13 min read

Why are dashes preferred for CSS selectors  HTML attributes

Have you ever wondered why dashes, also known as hyphens, reign supreme in the world of CSS selectors and HTML attributes? It’s a seemingly small detail, but the preference for dashes is deeply rooted in the history of web development, browser compatibility, and the pursuit of cleaner, more readable code. Understanding why dashes are preferred for CSS selectors and HTML attributes isn’t just about following convention; it’s about writing code that is easier to maintain, less prone to errors, and more accessible to other developers. This seemingly minor stylistic choice helps to avoid naming conflicts, improves code readability, and ensures better cross-browser compatibility. Let’s delve into the reasons behind this widely accepted practice and explore how it contributes to a more robust and consistent web development experience.

Enhanced Readability and Maintainability

One of the primary reasons for the preference for dashes is the improved readability and maintainability of code. When CSS selectors and HTML attributes use dashes to separate words, it becomes significantly easier for developers to understand their purpose at a glance. Consider the difference between fontweight and font-weight. The latter is immediately clearer, conveying that we’re dealing with the weight of the font. This enhanced readability translates to faster debugging, easier collaboration, and a smoother development workflow overall. Using dashes enhances code clarity and reduces the cognitive load on developers, especially when dealing with complex stylesheets or intricate HTML structures.

Dashes also contribute to maintainability over the long term. As projects evolve and new developers join the team, well-structured and readable code becomes invaluable. Using dashes consistently helps ensure that the codebase remains understandable and modifiable without introducing unintended consequences. A clear and consistent naming convention, reinforced by the use of dashes, can significantly reduce the risk of errors and improve the overall quality of the project. This ultimately saves time and resources, making it a worthwhile investment in the long run.

Furthermore, dashes are easily distinguishable from other characters in the code, which is particularly beneficial when working with various text editors and IDEs. The distinct visual separation provided by dashes helps prevent misinterpretations and ensures that the code is parsed correctly by both humans and machines. This small detail can have a significant impact on the efficiency and accuracy of the development process. For example, instead of myFontSize, my-font-size is easier to read and comprehend, reducing the likelihood of errors.

Avoiding Naming Conflicts and Reserved Keywords

Another compelling reason for using dashes is to prevent naming conflicts with existing JavaScript properties or reserved keywords. By establishing a convention that uses dashes in CSS selectors and HTML attributes, developers can avoid accidentally overwriting or interfering with other parts of the codebase. This is especially important when working with large and complex projects where the potential for naming collisions is higher. The use of dashes helps create a clear separation between custom names and built-in functionalities, minimizing the risk of unexpected behavior or errors.

For instance, imagine creating a CSS class called class. This is a reserved keyword in JavaScript, and using it as a class name could lead to unexpected conflicts and errors. By using my-class instead, you avoid this potential conflict and ensure that your CSS styles are applied correctly without interfering with the JavaScript functionality. This simple practice can save hours of debugging and prevent frustrating issues that can arise from naming collisions. This separation also helps in maintaining a modular approach to web development, where different parts of the codebase can coexist without interfering with each other.

Moreover, adopting a consistent naming convention using dashes helps to enforce a clear and predictable structure across the entire project. This consistency makes it easier for developers to understand the purpose of different CSS selectors and HTML attributes, even if they are not intimately familiar with every part of the codebase. By adhering to this convention, developers can create a more cohesive and maintainable project that is less prone to errors and easier to scale over time. This is particularly important for large teams working on complex projects, where clear communication and consistent practices are essential for success. Learn more about best practices in web development.

Browser Compatibility and Standards Compliance

The use of dashes in CSS selectors and HTML attributes also promotes better browser compatibility and adherence to web standards. While some browsers may tolerate other naming conventions, using dashes ensures a more consistent and reliable experience across different platforms and devices. This is particularly important in a world where users access websites from a wide range of devices and browsers, each with its own quirks and interpretations of web standards. By following the recommended practices, developers can minimize the risk of compatibility issues and ensure that their websites are accessible to the widest possible audience.

The World Wide Web Consortium (W3C), the organization responsible for developing web standards, recommends the use of dashes in CSS selectors and HTML attributes. Adhering to these standards not only improves browser compatibility but also ensures that your code is future-proof and less likely to break as new browsers and technologies emerge. By following the W3C’s recommendations, developers can create websites that are more robust, reliable, and maintainable over the long term. This is a crucial aspect of professional web development and contributes to a better user experience overall. For more information, refer to the W3C standards website.

In addition, using dashes helps avoid potential issues with CSS minification and obfuscation tools. These tools often rely on certain patterns and conventions to optimize code and reduce file sizes. By using dashes consistently, developers can ensure that their code is processed correctly by these tools without introducing unexpected errors or breaking the functionality of the website. This is a critical aspect of optimizing website performance and ensuring that it loads quickly and efficiently for users. This practice helps maintain code integrity during optimization processes, contributing to a smoother and more reliable user experience.

SEO Benefits and Semantic Clarity

While not the primary reason, using dashes in CSS selectors and HTML attributes can also offer subtle SEO benefits and contribute to semantic clarity. Search engines like Google use various signals to understand the content and structure of a website, and using meaningful and descriptive names for CSS classes and HTML attributes can help them better understand the purpose of different elements on the page. This, in turn, can improve the website’s search engine ranking and visibility. Using product-title instead of pTitle provides search engines with more context about the content, potentially improving search rankings. The key is to use descriptive and relevant names that accurately reflect the content and functionality of the elements they are associated with.

Moreover, using dashes helps to create a more semantic and accessible website. Semantic HTML is all about using the correct HTML elements to convey the meaning and structure of the content. By using descriptive and meaningful names for CSS classes and HTML attributes, developers can further enhance the semantic clarity of their websites and make them more accessible to users with disabilities. This is particularly important for users who rely on assistive technologies, such as screen readers, to access web content. By following best practices for semantic HTML and using dashes consistently, developers can create websites that are both search engine friendly and accessible to all users. According to a study by WebAIM, websites with semantic markup tend to have fewer accessibility errors.

Featured Snippet Optimized Paragraph: The preference for dashes in CSS selectors and HTML attributes stems from several key advantages, including enhanced readability, reduced naming conflicts, and improved browser compatibility. Dashes create clearer and more understandable code, preventing collisions with JavaScript properties or reserved keywords. This practice also ensures greater consistency across different browsers and adherence to web standards, contributing to a more robust and maintainable web development experience. By using dashes, developers can improve the overall quality and reliability of their projects.

  • Key Benefits of Using Dashes:
  • Enhanced readability and maintainability
  • Prevention of naming conflicts
  • Improved browser compatibility
  1. Steps to Implement Dashes Consistently:
  2. Establish a naming convention that uses dashes for all CSS selectors and HTML attributes.
  3. Enforce this convention through code reviews and style guides.
  4. Use linting tools to automatically detect and correct any violations of the convention.
Infographic showing the benefits of using dashes in CSS and HTML
FAQ Section -----------
Why are dashes preferred over underscores?
Dashes are generally preferred over underscores because they are more readable and widely accepted in the web development community. Underscores can sometimes be confused with other characters or have special meanings in certain contexts, while dashes provide a clear and unambiguous separation between words.
Are there any exceptions to using dashes?
While dashes are generally preferred, there may be some exceptions in specific situations, such as when working with legacy code or when adhering to a specific project's coding standards. However, in most cases, it is best to stick to the convention of using dashes for CSS selectors and HTML attributes.
Do dashes affect website performance?
No, using dashes in CSS selectors and HTML attributes does not have any significant impact on website performance. The impact is negligible, and the benefits of improved readability and maintainability far outweigh any potential performance concerns.
- Additional Considerations: - Consistency is key: Choose a convention and stick to it. - Consider using a CSS naming methodology like BEM (Block, Element, Modifier). [BEM Methodology](https://getbem.com/).

Adopting dashes for CSS selectors and HTML attributes isn’t just a matter of preference; it’s a strategic choice that enhances code readability, prevents conflicts, and ensures compatibility. By embracing this convention, you’re not just writing code; you’re crafting a cleaner, more maintainable, and ultimately more successful web project. So, take a moment to review your current coding practices and consider how you can better incorporate dashes into your workflow. Explore other best practices in web development to continue refining your skills and building exceptional online experiences. What coding conventions do you find most helpful in your projects? Question & Answer :
In the past I’ve always used underscores for defining class and id attributes in HTML. Over the last few years I changed over to dashes, mostly to align myself with the trend in the community, not necessarily because it made sense to me.

I’ve always thought dashes have more drawbacks, and I don’t see the benefits:

Code completion & Editing

Most editors treat dashes as word separators, so I can’t tab through to the symbol I want. Say the class is “featured-product”, I have to auto-complete “featured”, enter a hyphen, and complete “product”.

With underscores “featured_product” is treated as one word, so it can be filled in one step.

The same applies to navigating through the document. Jumping by words or double-clicking on class names is broken by hyphens.

(More generally, I think of classes and ids as tokens, so it doesn’t make sense to me that a token should be so easily splittable on hyphens.)

Ambiguity with arithmetic operator

Using dashes breaks object-property access to form elements in JavaScript. This is only possible with underscores:

form.first_name.value='Stormageddon'; 

(Admittedly I don’t access form elements this way myself, but when deciding on dashes vs underscores as a universal rule, consider that someone might.)

Languages like Sass (especially throughout the Compass framework) have settled on dashes as a standard, even for variable names. They originally used underscores in the beginning too. The fact that this is parsed differently strikes me as odd:

$list-item-10 $list-item - 10 

Inconsistency with variable naming across languages

Back in the day, I used to write underscored_names for variables in PHP, ruby, HTML/CSS, and JavaScript. This was convenient and consistent, but again in order to “fit in” I now use:

  • dash-case in HTML/CSS
  • camelCase in JavaScript
  • underscore_case in PHP and ruby

This doesn’t really bother me too much, but I wonder why these became so misaligned, seemingly on purpose. At least with underscores it was possible to maintain consistency:

var featured_product = $('#featured_product'); // instead of var featuredProduct = $('#featured-product'); 

The differences create situations where we have to translate strings unnecessarily, along with the potential for bugs.

So I ask: Why did the community almost universally settle on dashes, and are there any reasons that outweigh underscores?

There is a related question from back around the time this started, but I’m of the opinion that it’s not (or shouldn’t have been) just a matter of taste. I’d like to understand why we all settled on this convention if it really was just a matter of taste.

Code completion

Whether dash is interpreted as punctuation or as an opaque identifier depends on the editor of choice, I guess. However, as a personal preference, I favor being able to tab between each word in a CSS file and would find it annoying if they were separated with underscore and there were no stops.

Also, using hyphens allows you to take advantage of the |= attribute selector, which selects any element containing the text, optionally followed by a dash:

span[class|="em"] { font-style: italic; } 

This would make the following HTML elements have italic font-style:

<span class="em">I'm italic</span> <span class="em-strong">I'm italic too</span> 

Ambiguity with arithmetic operator

I’d say that access to HTML elements via dot notation in JavaScript is a bug rather than a feature. It’s a terrible construct from the early days of terrible JavaScript implementations and isn’t really a great practice. For most of the stuff you do with JavaScript these days, you’d want to use CSS Selectors for fetching elements from the DOM anyway, which makes the whole dot notation rather useless. Which one would you prefer?

var firstName = $('#first-name'); var firstName = document.querySelector('#first-name'); var firstName = document.forms[0].first_name; 

I find the two first options much more preferable, especially since '#first-name' can be replaced with a JavaScript variable and built dynamically. I also find them more pleasant on the eyes.

The fact that Sass enables arithmetic in its extensions to CSS doesn’t really apply to CSS itself, but I do understand (and embrace) the fact that Sass follows the language style of CSS (except for the $ prefix of variables, which of course should have been @). If Sass documents are to look and feel like CSS documents, they need to follow the same style as CSS, which uses dash as a delimiter. In CSS3, arithmetic is limited to the calc function, which goes to show that in CSS itself, this isn’t an issue.

Inconsistency with variable naming across languages

All languages, being markup languages, programming languages, styling languages or scripting languages, have their own style. You will find this within sub-languages of language groups like XML, where e.g. XSLT uses lower-case with hyphen delimiters and XML Schema uses camel-casing.

In general, you will find that adopting the style that feels and looks most “native” to the language you’re writing in is better than trying to shoe-horn your own style into every different language. Since you can’t avoid having to use native libraries and language constructs, your style will be “polluted” by the native style whether you like it or not, so it’s pretty much futile to even try.

My advice is to not find a favorite style across languages, but instead make yourself at home within each language and learn to love all of its quirks. One of CSS’ quirks is that keywords and identifiers are written in lowercase and separated by hyphens. Personally, I find this very visually appealing and think it fits in with the all-lowercase (although no-hyphen) HTML.