Is having multiple classes in an element a good (o

2019-10-07 03:39发布

Is having multiple classes in a single element a good practice? Like so:

<div class ="panel panel-primary panel-hide text-center">

Or is it better to do this:

<div class ="panel">
    <div class="panel-primary">
        <div class="panel-hide">
            <div class="text-center">
             <!-- content here -->

Or is it better to limit classes to 2 or 3 per div?

Or does it even matter?

2条回答
Viruses.
2楼-- · 2019-10-07 03:54

Depends on the project, what you're trying to accomplish, and what pre-existing helpers you're using.

If you're using something like Twitter Bootstrap, use what you're given to accomplish what you need in the least amount of code.

If you're building something with custom classes, stick with one pattern and follow through. You want to be conscious of why you're adding a class, otherwise you can run into specificity problems later down the line and resort to adding more on top just to pinpoint a particular element.

If adding a class will save 10 lines of repeated code, as you repeat the same styles with like items, absolutely go for it. However, I like to try to keep the classes as streamlined as possible.

A very boiled down example:

THIS

<div class="one">
   <p>
       <h1>Hi there!</h1>
   </p>
</div>

.one {
    /* css here */
}

.one > p {
    /* more css here */
}

.one > p > h1 {
    /* even more css here */
}

COULD WORK INSTEAD OF ALL THIS

<div class="one">
   <p class="one-p">
       <h1 class="one-header">Hi there!</h1>
   </p>
</div>

.one {
    /* css here */
}

.one .one-p {
    /* more css here */
}

.one .one-p .one-header {
    /* even more css here */
}
查看更多
Ridiculous、
3楼-- · 2019-10-07 04:03

Did you got some of these classes and pieces of code from the Bootstrap website?

Sometimes classes need to be on separate nested divs, because they use :before and :after or margin, padding or positioning for that div. When you paste all classes inside one div, this may not work, and classes may overwrite eachother.

查看更多
登录 后发表回答