Reputation: 4072
I have a page where there's a tag with an id
, but a normal css class, like this one:
<div id='stack_overflow_example' class='title'> ... </div>
As everybody knows, this id
have to be unique on that page, and I'm using it only to easily find it under css (could be used for ajax requests, for example, but this is not the case).
Reading about css locators (selectors), I found that I should not use IDs as css selectors, because this would tightly couple my css code with my html code.
Alright, I agree. But the option is to put a unique css class on that tag, and then use it on css code.
Why this option is not as tightly coupled as the first one?
Could anybody give any other reason than what I just thought: "Because on this second option, you can reuse the 'unique' css on other 'unique' tags too."
EDITED: Thinking about performance reason, my friend just thought (and I agreed):
unique
Isn't it, on the end of the edge, a performance glitch making option 1 sound better?
Upvotes: 3
Views: 1869
Reputation: 9759
It sounds like you are understanding it more or less correctly. While imo there are situations where using an ID in a css selector is the right thing to do, the advantage of a class is not only that it can apply to more than one element on the page, but also that you can have more than one class per element which makes them easier to reuse. (Imagine a case where I want to reuse some style rules that are currently being applied via an ID selector, however the element that I want to apply these to already is getting a set of style rules from another ID selector...can't give that element two IDs. With classes, you won't run into this)
Upvotes: 0
Reputation: 723618
You can apply one unique ID to any one element in each page. It doesn't matter which element has the ID as long as only one has it per page. There is no such rule for classes. Hence the coupling issues you're referring to (i.e. the CSS has a very rigid assumption that the element with a certain ID serves the same presentation and purpose across any HTML pages it's applied to).
Honestly I wouldn't really care about coupling (EDIT: or performance) issues so much. If I have an ID and I wish to apply styles only to that ID, I select by that ID. If the element shares that class with other elements and I want to apply styles to all elements with that class, I select by that class.
Upvotes: 2