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

后端 未结 20 2058
谎友^
谎友^ 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:19

    The main problem with having classes named floatleft, clear or the like is the fact that changes in the design imply changes in the HTML markup. This should not happen, true separation between content and presentation is achieved only when you can re-use the same markup in multiple designs or even media (think sharing the same HTML between desktop and mobile versions of your site and only switching sylesheets).

    Now, for a practical example :). To add on Fredrik's answer, LESSCSS allow you to hide styles declarations/mixins from developers. This way you can protect reusable components in your stylesheets without the danger of having them pop up in your HTML.

    Sample markup:

    <div class="branding">Company Name</div>
    

    Sample less code:

    // example of reusable functions
    .noText() {
        color: transparent;
        text-indent: -9999px;
    }
    .clear-after() {
        &:after {
            content: ".";
            display: block;
            visibility: hidden;
            height: 0;
            clear: both;
        }
    }
    
    .branding {
        .clear-after();
        .noText();
        background-image: ...;
    }
    

    Of course, for mobile you might just want to have the company name in bold, without any other styling:

    .branding {
        color: pink;
        font-weight: bold;
    }
    
    0 讨论(0)
  • 2020-12-13 09:21

    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.

    0 讨论(0)
提交回复
热议问题