What's the best way to name IDs and classes in

2019-01-22 09:26发布

When naming classes and IDs for CSS what is the best method to use. In this case I need there to be some kind of naming convention so that other people can pick up rules and understand how to name their own ids and classes using the same pattern. Any suggestions? Some of the sites we create can get pretty complex but use an overall structure header, content and footer. The naming must be efficient too.

I am not new to CSS. I am aware of giving them names that represent their structure etc., but just want to know people opinions really and ways of doing this.

8条回答
Viruses.
2楼-- · 2019-01-22 09:47

There is no real naming convention. Just agree on one with your team and keep it consistent. For instance don't mix camel case and snake case.

Try to be as description as possible when naming a class. Example:

.menu: bad
.head_menu: better

.wrapper: very bad
.main_content_wrapper: better

edit; Worse naming convention I saw is using the actual content of the styling. For instance:

.redButton

... because when I got to the code (legacy code), but "red button" was not red but blue (or something like that).

Try to use something that will not likely change, like the purpose of the class.

查看更多
Summer. ? 凉城
3楼-- · 2019-01-22 09:59

The best advice is to use class with semantics in mind

Good names don't change

Think about why you want something to look a certain way, and not really about how it should look. Looks can always change but the reasons for giving something a look stay the same.

Good names warning, important, downloadableImage and submenu are all good names. They describe what a certain element represents, and they are not likely to change. A warning will always remain a warning, no matter how much the look of the page changes.

Bad names border4px, lighttext and prettybackground are all examples of bad names. You might fatten that border to a whopping 5 pixels, or the background may look pretty old after a while, and not pretty at all. An advantage of using CSS is that you won't have to change much in order to change the looks of your website. If you have to change all light text into dark text, and thus change all classes lighttext to darktext in all your HTML pages, you're likely to miss a few.

from this article

查看更多
登录 后发表回答