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

后端 未结 20 2126
谎友^
谎友^ 2020-12-13 08:32

Lots of websites use class names like floatleft, clearfloat, alignright, small, center etc that describe the

20条回答
  •  轮回少年
    2020-12-13 09:00

    Presentational class names

    The HTML spec is clear on this issue:

    There are no additional restrictions on the tokens authors can use in the class attribute, but authors are encouraged to use values that describe the nature of the content, rather than values that describe the desired presentation of the content.

    Does clearleft describe the nature of the content? Not really. Eric Meyer made a joke about this a while ago.

    enter image description here

    Try to find a structural relation between the seemingly unrelated elements

    Let's say you have paragraphs about ducks, paragraphs about monkeys and paragraphs about frogs. You want them have a blue background.

    You could add this CSS rule:

    p.duck, p.monkey, p.frog {
        background-color: blue;
    }
    

    But aren't they all animals? Just add another animal token:

    And change the CSS rule to:

    p.animal {
        background-color: blue;
    }
    

    It is hard and it might not always be possible but the important thing is not to give up quickly.

    What if you can't?

    If you have a lot of elements with absolutely no structural relation between them, that indicates a structural problem with your document. Try to decrease these elements. That said, grouping n CSS selectors on one rule is still better than adding n presentational class tokens in your HTML document.

提交回复
热议问题