CSS Class Naming Convention

CSS class naming convention

The direct answer to the question is right below this one, by Curt.

If you're interested in CSS class naming conventions I suggest to consider one very useful convention named BEM (Block, Element, Modifier).

UPDATE

Please read more about it here - http://getbem.com/naming/ - that's a newer version that renders the following answer obsolete.


Main principles:

  • A page is constructed from independent Blocks. Block is an HTML element which class name has a "b-" prefix, such as "b-page" or "b-login-block" or "b-controls".

  • All CSS selectors are based on blocks. There shouldn't be any selectors that aren't started with "b-".

Good:

.b-controls .super-control { ... }

Bad:

.super-control { ... }
  • If you need another block (on the another page maybe) that is similar to block you already have, you should add a modifier to your block instead of creating a new one.



Example:

<div class="b-controls">
<div class="super-control"></div>
<div class="really-awesome-control"></div>
</div>

With modifier:

<div class="b-controls mega"> <!-- this is the modifier -->
<div class="super-control"></div>
<div class="really-awesome-control"></div>
</div>

Then you can specify any modifications in CSS:

.b-controls { font: 14px Tahoma; }
.b-controls .super-control { width: 100px; }

/* Modified block */
.b-controls.mega { font: 20px Supermegafont; }
.b-controls.mega .super-control { width: 300px; }

If you have any questions I'd be pleased to discuss it with you. I've been using BEM for two years and I claim that this is the best convention I've ever met.

Best Practice on Naming CSS class selector for a same tag, but different behavior

The concept of naming the CSS classes as such as known as the BEM nomenclature/method, which is an acronym for block-element-modifier. What BEM does is that it advocates for a clear and standardised way of naming your CSS classes, so that you do not get easily confused.

The BEM method is what that inspires the CSS classes you come across. In your question, you mentioned btn and btn-default. In strict BEM sense, that would be btn and btn--default, since "default" is a modifier/state. However, different authors and frameworks have different means of separating these terms, so btn-default is just as legitimate as btn--default—as long as you are consistent throughout your stylesheet.

In this case, btn is the base class of all button-like elements. It likely contains some base styles (like padding, line-height, positioning). btn-default is an extension of the btn class, perhaps containing colors for the "default look" of the button (I can imagine authors having a standard call-to-action color for buttons). Declaring btn-default itself does not make sense, because it extends on or modifies the btn class, which means it lacks the base styles of what is intended to be a button.

Based on this logic, even when item does not have any styles explicitly tied to it, you should still include it in your markup, along side with item--important, for example. Using item--important itself has no meaning.

If you would indulge me in a rather more verbose example, let's say you have the following layout: you want a <div> that spans the full width of a container, and sometimes you wanted it to expand beyond the container, and etc...:

body {  background-color: #ccc;  margin: 0;  padding: 0;}
section { background-color: #fff; margin: 1.5rem 3rem; position: relative;}

/* Base styles for .content */
.content { background-color: #eee; margin-bottom: 1.5rem; padding: 1rem;}

/** * Modifier: expand * Now, we want to increase the width */.content--expand { position: relative; left: -3rem; width: calc(100% + 6rem);}
/** * Modifier: important * Now, we want to draw attention to this content */ .content--important { background-color: #b13131; color: #fff; }
<section>  <div class="content">I am content, with default styles</div>  <div class="content content--expand">I am content, with expanded width. Note that I inherit base styles from my `.content` block</div>  <div class="content--expand">I am expanded width content without using `.content`. Look that I am messed up.</div>  <div class="content content--important">I am a very important content.</div></section>

React className naming convention

TLDR: PascalCase and Block__Element--Modifier

Check out the official doc of create-react-app. It provides a minimum example of creating a custom component. The js and css filenames as well as the className are all following PascalCase.

// Button.css
.Button {
padding: 20px;
}

// Button.js
import React, { Component } from 'react';
import './Button.css'; // Tell Webpack that Button.js uses these styles

class Button extends Component {
render() {
// You can use them as regular CSS styles
return <div className="Button" />;
}
}

Besides, the doc also provides an external link, which describes BEM naming conventions (link) for elements inside the component.

// MyComponent.js
require('./MyComponent.less');
import { Component } from 'react';
export default class MyComponent extends Component {
render() {
return (
<div className="MyComponent">
<div className="MyComponent__Icon">Icon</div>
...
</div>
);
}
}

// MyComponent.less
.MyComponent__Icon {
background-image: url('icon.svg');
background-position: 0 50%;
background-size: fit;
height: 50px;
}

What is the standard naming convention for html/css ids and classes?

There isn't one.

I use underscores all the time, due to hyphens messing up the syntax highlighting of my text editor (Gedit), but that's personal preference.

I've seen all these conventions used all over the place. Use the one that you think is best - the one that looks nicest/easiest to read for you, as well as easiest to type because you'll be using it a lot. For example, if you've got your underscore key on the underside of the keyboard (unlikely, but entirely possible), then stick to hyphens. Just go with what is best for yourself. Additionally, all 3 of these conventions are easily readable. If you're working in a team, remember to keep with the team-specified convention (if any).

Update 2012

I've changed how I program over time. I now use camel case (thisIsASelector) instead of hyphens now; I find the latter rather ugly. Use whatever you prefer, which may easily change over time.

Update 2013

It looks like I like to mix things up yearly... After switching to Sublime Text and using Bootstrap for a while, I've gone back to dashes. To me now they look a lot cleaner than un_der_scores or camelCase. My original point still stands though: there isn't a standard.

Update 2015

An interesting corner case with conventions here is Rust. I really like the language, but the compiler will warn you if you define stuff using anything other than underscore_case. You can turn the warning off, but it's interesting the compiler strongly suggests a convention by default. I imagine in larger projects it leads to cleaner code which is no bad thing.

Update 2016 (you asked for it)

I've adopted the BEM standard for my projects going forward. The class names end up being quite verbose, but I think it gives good structure and reusability to the classes and CSS that goes with them. I suppose BEM is actually a standard (so my no becomes a yes perhaps) but it's still up to you what you decide to use in a project. Most importantly: be consistent with what you choose.

Update 2019 (you asked for it)

After writing no CSS for quite a while, I started working at a place that uses OOCSS in one of their products. I personally find it pretty unpleasant to litter classes everywhere, but not having to jump between HTML and CSS all the time feels quite productive.

I'm still settled on BEM, though. It's verbose, but the namespacing makes working with it in React components very natural. It's also great for selecting specific elements when browser testing.

OOCSS and BEM are just some of the CSS standards out there. Pick one that works for you - they're all full of compromises because CSS just isn't that good.

Update 2020

A boring update this year. I'm still using BEM. My position hasn't really changed from the 2019 update for the reasons listed above. Use what works for you that scales with your team size and hides as much or as little of CSS' poor featureset as you like.

What is the naming convention for CSS classes for styling and for events?

Just use "js-" in the begining of all classes used for JS events.

Is there a standard method for naming classes?

To be perfectly honest, this comes down to individual developers and their own feelings. There are two equally good ways of structuring CSS classes, just like you suggested:

.profile.image.large{
width: 300px;
}

/* Or: */
.profile-image-large{
width:300px;
}

They achieve the same thing, but when you start thinking broadly, you see just how wide the gap between these styles becomes.

Separating classes makes them re-usable: The DRY convention is to never repeat yourself. By separating the large or image classes, we can reuse the same class:

.blue{
border: 3px solid blue; /* All .blue's will have a blue border */
}

.profile.blue{
border-style: dashed; /* Inherits from the previous blue and replaces the solid with a dash. */
}

In the second approach - using - separators, the code would be:

.blue{
border: 3px solid blue; /* All .blue's will have a blue border */
}

.profile-blue{
border: 3px dashed blue; /* We had to redefine the entire style */
}

On a simple example like a border, this doesn't seem to matter. But take into account a much larger CSS chunk that you may want to re-use dozens of times throughout your code. You'll be repeating yourself a lot.

Logically grouping styles is still a good thing: I'm not saying that -classes are a bad thing - they help define a namespace for your code, so in the sense of maintaining modular code, prefixing your styles with an identifier will help prevent conflicts, especially if you're developing code inside a web agency that will be re-used, or if you're building a plugin (in which case, style prefixing is absolutely needed).

Developing in a compiled language like SCSS (my preferred environment) changes how you think too. In SASS/SCSS we can easily do this:

.profile{
display: block;

&-image{
border: 1px solid blue;
}
}

And that evaluates to the same as profile profile-image on the element. Alternatively SASS also supports:

.profile{
display: block;

&.image{
border: 1px solid blue;
}
}

Which evaluates to profile image on an element. Very similar - but both styles are restricted to their parent element .profile and can't be used globally. The styles are protected, whereas in my first 'natural' CSS example, the blue class could freely be added and incorporated by any element in the HTML page.

Edit: You could still use a global .image style in your SASS code, and then override individual examples, but personally, I feel this violates the DRY principle and I try to avoid doing it where possible.

So what's the TL;DR?

In my opinion, there's no "right answer". From a conventions standpoint, it's worth noting that frameworks like Twitter-Boostrap use a hybrid of the two styles - global classes that can be applied everywhere, mixed with prefixed classes that protect their children's styles.

The most important thing for any programmer is that your code is clearly readable and defined, and that you use as little code as possible to achieve your result - no matter what method you use.

Can the id and a class have the same name of an html element?

Yup, you absolutely can. If you’re the only one working on the project, and if this is intuitive to you, go right ahead, no issues.

But when working with a larger team, it generally makes sense to use ids and classes that are little more descriptive in nature. For example, .left-primary-sidebar would tell me a whole lot more about the element than something like .aside, when going through the stylesheet.

Your naming choices are definitely valid.

Naming conventions can differ from company to company, so if you’re the only one working on the repo, you can set your own conventions.

Best practice for CSS class naming for use with jQuery selectors

Trying to deal with unique names can work well for small projects, but the larger you get the more likely you will have conflicts.

That is why I like the second approach.

However, to make it easier, you can use SASS, to pre process your css files. You can then do nesting like this:

#list {
.delete {
}
.items {
.item {
}
}
}

And you will get code similar to your second example, without having to write it all out.

As for the jQuery selectors, those would still need to be written out longhand if you wanted to do it that way, but having complex selectors like that is often considered a sign of a bad design.



Related Topics



Leave a reply



Submit