Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
403 views
in Technique[技术] by (71.8m points)

html - Should css class names like 'floatleft' that directly describe the attached style be avoided?

Lots of websites use class names like floatleft, clearfloat, alignright, small, center etc that describe the style that is attached to the class. This seems to make sense so when writing new content you can easily wrap (for example) <div class="clearfloat">...</div> around your element to make it behave the way you want.

My question is, doesn't this style of naming classes go against the idea of separating content from presentation? Putting class="floatleft" on an element is clearly putting presentation information into the HTML document.

Should class names like this that directly describe the attached style be avoided, and if so what alternative is there?


To clarify, this isn't just a question of what to name classes. For example a semantically accurate document might look something like:

<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...
<div class="foobar">Another unrelated topic</div>

Say all these divs need to clear floats, the css would look something like:

div.foo, div.bar, div.foobar {
    clear:both;
}

This starts to get ugly as the number of these clearing elements increases - whereas a single class="clearfloat" would serve the same purpose. Is it recommended to group elements based on the attached styles to avoid repetition in the CSS, even if this means presentational information creeps into the HTML?


Update: Thanks for all the answers. The general consensus seems to be to avoid these class names in favour of semantic names, or at least use them sparingly provided they don't hinder maintenance. I think the important thing is that changes in the layout should not require excessive changes to the markup (although a few people said minor changes are okay if it makes overall maintenance easier). Thanks to those who suggested other methods to keep CSS code smaller as well.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

It's great until you re-design, and narrow is highlighted yellow, center converts better left-justified, and the image you called floatleft now belongs on the right.

I'll admit to the sin of using floatleft and clear as CSS class names, but it is much easier to maintain your CSS if you choose names that relate to the semantic meaning of the content, like feedback and heroimage.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...