问题
Let's say I'm building a blog and add a class named "post" for the timeline posts. Then another developer comes in and creates a highlights section which also has a "post" class. All of a sudden we have a collision.
I usually solve this by nesting classes and not keeping anything "global" but from what I've understood it's not best practice:
.main .post {
background-color: red;
}
.highlights .post {
background-color: green;
}
When I inspect big sites CSS files I see loads of global class names for seemingly specific parts of the page so I'm really wondering how they solve it. Do they search and scan the whole project for a class name before adding it? What do they do if they want to add something which already exists? Renaming it just for the sake of it seems like a really bad practice if anything.
回答1:
The secret is to use some sort of framework/methodology that enforces discipline e.g. OOCSS or BEM.
回答2:
There are several CSS classes naming conventions around and one of the most used is BEM (http://csswizardry.com/2013/01/mindbemding-getting-your-head-round-bem-syntax/). Take a look :)
来源:https://stackoverflow.com/questions/21828894/how-do-you-avoid-class-name-collisions