Cascading style sheets use “id” or “class”

后端 未结 15 2508
夕颜
夕颜 2020-12-05 16:11

when styling specific html elements, i tend to always use the class attribute. the css code looks cleaner imo.

why do both exist which one should you use and when ?<

15条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-05 16:42

    For CSS purposes, I share your habit of only using class. When JavaScript needs to touch elements, I'll give them ids as well, but I don't style on the id from my stylesheets.

    My reasons for this are simple: It's always possible that, somewhere down the road, you might need another one. If you style it by class, you can just add a second element with that class and you're good to go. If you style it by id, then you need to either change the id to a class or (if there's any code referencing the id) split the id into both an id and a class and then figure out how to divide up the attributes and references between them. Much easier to just style it by class to start with.

    I also prefer classes because you can assign more than one to the same element, which helps to avoid pointless repetition in the stylesheet, although this is a weak argument given that there's no reason you can't do some styling on id and other styling based on an arbitrary number of classes.

提交回复
热议问题