简体   繁体   中英

Is it bad practice to reuse the same class multiple times, but holding different styles?

For example, I want to do something on the first <li class="first"> of a <ul> list.

and I write the CSS:

ul .first{
    /*awesome code here*/
}

But then, I also want to give a particular CSS to the first <p class="first"> of my <div id="content"> .

and I do it like this:

#content .first{
    /*awesome code here*/
}

In case you didn't noticed, I reused the class first to give totally different styles to two totally different cases.

  • Is it bad to reuse classes in this way?
  • Is there any possibility that this lead to glitches/bugs?

It's fine by me because when you are intentionally defining what the first item and paragraph of your structure will look like. Although, it'd be better if you used :first-child pseudo selector but then again both will have different styles because that's what you want.

I hope I'm not missing the big picture here but I'm also wondering what you meant with code reusability in this case?

If you are going to use ul.first then you have to change your

<li id="first" to <li class="first"

You have errors in your CSS.

If you want to apply a rule to the first li in ul , assuming you have the following HTML:

<ul>
    <li class="first">Something</li>

Your css should look like this

ul .first {
/* Some code here, notice the space above */
}

The same goes with your second statement. By writing #content.first you are saying "I mean an object that has an id like content and has the first class". If you add a space, #content .first , you then mean "I want to select an object that has the first class and sits within an object that has the id content assigned to it".

But to answer your question, this is not bad practice, on the contrary - it is recommended for semantic reasons.

You should only use this approach when you're sharing styles across elements. That's actually one of the reasons for having classes in CSS. It's so you don't have to repeat the same style for different elements. If you try to apply two different values for the same property then the initial value will be overwritten.

For example:

.first
{
color: blue;
color: red; 
}

The second style will overwrite the first. Also, even if you don't overwrite the original property, you can still run into issues debugging style bugs. For example, you have inline elements and block level elements so in those cases you may run into issues using this approach.

Updated: Made blanket statement about CSS classes more general. ;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM