This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 7 years ago.
<div id="stockexchange-id" class="stockexchange-class">Text</div>
In the example above I added both a class and an id into the div statement. Is there a difference between them? If I call .stockexchange-class CSS instead of #stockexchange-id CSS does it make any difference? If it doesn't then what it the point of having both of them? Also which one would be better to use?
The biggest difference is that a document can have multiple elements with the same class, but not with the same ID. An Identifier must be specific to a certain element within a document (i.e. full HTML page).
When applying CSS styling, some experts have recommended using classes over IDs to avoid specificity wars. CSS Lint (http://csslint.net/) recommends this.
The reason is that stylesheets are read from top to bottom, but IDs take precedence over class. This means that:
#stockexchange-id {
color: blue;
}
.stockexchange-class {
color: red;
}
Would color the text blue, even though red comes later. Here's a good graphic explaining specificity: https://stuffandnonsense.co.uk/archives/images/specificitywars-05v2.jpg.
If everything has the same specificity, and most styles are applied via a single class, it makes the CSS easier to reason about, since it will read from top to bottom without extra styles being mixed in different orders. It also makes it easier to override classes, which can be useful.
Finally, if you style based on classes, you can re-use the styling on the same page by applying the class to another element on the page. With IDs, since they are unique, you cannot do this. Even if you think an element is unique on a page (e.g. a Buy Button), this may not always be the case. A designer may request the same element again later in the page.
You can only use an ID name once in any XHTML or HTML document. Duplicate ID tags will cause your page to fail validation, and can have negative effects when using JavaScript with them. Simply put, an ID is like the sticker that says "you are here" on a mall directory, and there can only ever be one of those.
Classes, like ID's, can also be used to in JavaScript scripts, but unlike ID's, they can be used multiple times in the same HTML document. This separation of content from presentation is what makes sites powered by CSS more robust, but some don't know the full extent to which they can use classes.
Related
This question already has answers here:
What is the difference between id and class in CSS, and when should I use them? [duplicate]
(15 answers)
Closed 7 years ago.
So I often use a website LiveWeave.com to test HTML, CSS, and JavaScript code that I've written. It has a syntax checker, and whenever I use an ID as a selector in the CSS section, it says that it is improper to use an ID as a selector.
I have demonstrated it in this Weaver. To the right of line three in the CSS window is a yellow icon, which, when hovered over, says that it is improper to use IDs as a selector. I was under the impression that that is specifically for the purpose of being used as a selector for a single DOM element, as opposed to classes, which are designed to be applied to multiple DOM elements.
Am I wrong? IS it improper to use an ID as a selector?
The only other instance I can think of an ID being used is for JavaScript document.getElementById(), and similar functions. What is the proper use of an ID?
Note that I am NOT asking the difference between an ID and a Class, but rather whether it is proper to use an ID as a selector.
Using an ID is the most efficient way of selecting a DOM node in both CSS and Javascript. I personally like to use classes for all repeated items and ids for unique items, or unique configurations of repeated modules. There are many CSS patterns, I use a style called BEM (Block, Element, Modifier as seen here) which is a class based naming convention. Look at your favorite websites, right click or inspect. You will find that there is no one right answer to your question, only many right answers.
May I also say that both exist in the standard for a reason and serve a purpose depending on your applications needs.
Below is the order of efficiency for selectors. IDs are the most efficient and pseudo classes and pseudo elements are the least efficient.
id (#myid)
class (.myclass)
tag (div, h1, p)
adjacent sibling (h1 + p)
child (ul > li)
descendent (li a)
universal (*)
attribute (a[rel=”external”])
pseudo-class and pseudo element (a:hover, li:first)
See here...
It is not improper to use ID's as selectors, so long as the ID being used corresponds to only one element in the DOM (document object model).
If you'd like a selector that is multi-purpose, and able to be applied to multiple elements in the DOM, use a class. Although I'm sure you knew that.
The main reason ID's are frowned upon by some CSS developers, and full stack designers, is simply because they aren't as versatile and they have a higher specificity than classes, which can either help or hinder development (based on CSS knowledge).
For more information on CSS specificity, read here: https://css-tricks.com/specifics-on-css-specificity/
It's valid, it's just considered bad practice by some developers because it can make it difficult to maintain your CSS if you're not disciplined about it. I'm no expert on CSS but I'm pretty sure it's all to do with #'s having a really high specificity rating and if you have them dotted around your CSS files it makes it difficult to manage the cascade i.e. inheritance of style rules. So it's considered best by some to use IDs only for referencing elements in your JavaScript.
I've actually heard this argument before.
Some people push the idea of using solely classes for pure css stuff and keeping id for javascript and other id specific functionality.
It would seem that website follows that ideology, so they are trying to get their users to adopt it. I'm not sure if it is yet best practice to keep id out of css
You can decide for yourself whether an id is worth using, when you could just use a class instead.
If you used an ID as a selector and your using it in your Javascript too then you could make situation where if you decide to rename it then you've created a dependency that wouldn't be there if you had used a class name in your CSS.
Also, though using the ID is faster, it isn't faster if you then use #text a - since CSS reads right to left and has to check all the anchor elements first and then find the one with the ID of #text.
This also means the style isn't reusable and you can't use multiple classes either.
So I think the answer really is, based on all the pros and cons of using an ID as the selector, the best practice to keep you out of possible future problems is to not do it. Of course, this all really depends on how you code, the scope of the project and how many other people are working in the project. It's not against the rules, just not really best practice due to possible issues you might be building in that could bite you later.
On top of what has already been mentioned, even in CSS, ID's can be useful depending on what is the structural design.
For example; if every page in your website requires a header and a footer, I don't see why it would not be useful to make it an id.
What is wrong with doing:
#header {}
#footer {}
If you know for sure that your page has only one header and one footer, I don't see the point in using a class.
Mentioning the id is very specific and the page structure is undubious in this case.
Moreover, I also don't see what is wrong by doing something for example like:
.menu{}
#header .menu li{}
#footer .menu li{}
To add specific styling depending on the page segment. Seems very legit to me.
Ultimately, I even think that using ID's to indicate page sections might be more beneficial by ´knowing´ that they are unique (although they might be recurrent across different pages).
Reading an id in a CSS file should give the CSS designer the benefit of immediately knowing what page segment the following css rules are referring to.
A sheet with only classes would in that case seem less clear than using ID's imo.
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
I read an interesting post on using a css classname instead of the id attribute for identifying modules or widgets. The css classname could be prefixed with a hash or underscore, to indicate that the classname is used as an id. The reason for this being, that ids can only be used once per webpage whereas a module or widget could appear multiple times.
Simple Example
Instead of using ids such as
<div id="currencyConverter1" class="foo">EUR/USD</div>
<div id="currencyConverter2" class="foo">GB/USD</div>
prefixed classnames are used
<div class="#currencyConverter foo">EUR/USD</div>
<div class="#currencyConverter foo">GB/USD</div>
In the article it suggests, that an underscore could be used instead of a hash, because hashes need to be escaped.
I quite like this idea, but I'm not sure if this is good practice or has any drawbacks. What is the general opinion on this?
It doesn't get simpler than this: does it uniquely identify an element within a document tree now and forever? Use an ID. If not, use a class name.
Remember that IDs and classes are properties pertaining to each element, not a group of elements collectively. Using "identifier" to mean "identifying a group of elements" is futile; that's why you have class names instead, to classify those elements as being related in some manner.
If you're "identifying" elements that are members of a specific widget or module, you have free reign to add a class name to each element representing that widget or module, and select it in addition to the element's class:
<div class="my-module foo">.my-module.foo</div>
<div class="my-module bar">.my-module.bar</div>
Or, if specificity is such a huge issue that you can't even afford to stack another class selector to your rules, prefix the element's class name with the name of that module and select it.
<div class="my-module-foo">.my-module-foo</div>
<div class="my-module-bar">.my-module-bar</div>
If that's the question, then yes, it's perfectly legitimate — as I've mentioned, that's the whole point of class names and selectors.
But there are no legitimate benefits to making a class selector "look like" an ID selector without functioning like one. What it does cause, on the other hand, is needless confusion, especially for other authors who may not know better. If you want to avoid ID selectors like the plague, fine, leave them alone; nobody's forcing you to use them. But if you want to uniquely identify singular elements, then you may want to remember that CSS already provides a feature for that to complement the id attribute in HTML, known as the ID selector. There's no need to hack other parts of the selector syntax to emulate some other feature that's already readily available to you and has been since the very beginning.
Incidentally, if you're running into specificity issues with your CSS rules, then it's your CSS rules that need refactoring, not your markup. Hacking your markup to accommodate your style rules only leads to further trouble, at least in my experience. (I understand the irony in saying this given that hashes are allowed in identifiers starting with HTML5.)
Its mostly driven by your own, personal taste. there are a lot of opinions and articles on this topic, even complete books were written.
I suggest the following:
SMACSS
OOCSS
MVCSS
All of them are mentioning a more-or-less similiar naming convention for CSS, while also saying that these are just rules of thumb, not dogmas.
personally, i follow that approach:
.modName // module
.modName__sub // an object or sub-module
.modName__sub--modifier // a modifier
A similiar structure is used for example by InuitCSS
If you want to use classnames as unique identifiers, than just do it, there is nothing wrong about that. Further, it is future proof in case that you wish to use it as a "standard" class. However, i would shirk that hash for obvious reasons.
Not sure what your modules or widgets are for (wordpress?) but the methodology I choose to use when coding is this:
1: If it is DOM element that has a specific function that I know will only appear once on the page, then I use an ID (things like #main_navigation, #global_header).
2: The DOM element is used for styling purposes (CSS) then I use class names. I keep class names as descriptive of what the DOM element is doing as I can. I don't use vauge names like .blue_text (explained below).
3: I need to attach some sort of information to the DOM element that is kind of awkward and doesn't fit this scheme, then I use custom HTML data attributes. For example, if I create a backend for a site and a user can pick a background color for a div, instead of putting .user_selected_background_color_class as a class in the div I will instead write data="user_selected_color". This is a kind of lame example, but I just built something where a user can select a bunch of images to be in gallery mode or slideshow mode and I used data attributes to determine how the container div should be styled.
As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is the truly a best-practice in CSS: Using IDs and Classes or Selectors?
I have a stylesheet that is required by PHP once a form is submitted to style the results / successful-submission page and I was wondering what is a best-practise in CSS to use IDs and Classes or to use Selectors ?
Basically classes should be used for common page objects that may or could be repeated. ID's should only be used when there is a unique element on a page that you will not have anywhere else on the page.
One way to explain this would be:
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
There are no browser defaults for CLASSES and ID's
Adding a class name or ID to an element does nothing to that element by default.
This is something that snagged me as a beginner. You are working on one site and figure out that applying a particular class name fixes a problem you are having. Then you jump over to another site with the same problem and try to fix it with that same class name thinking the class name itself has some magical property to it only to find out it didn't work.
Classes and ID's don't have any styling information to them all by themselves. They require CSS to target them and apply styling.
ID's have special browser functionality
Classes have no special abilities in the browser, but ID's do have one very important trick up their sleeve. This is the "hash value" in the URL. If you have a URL like http://yourdomain.com#comments, the browser will attempt to locate the element with an ID of "comments" and will automatically scroll the page to show that element. It is important to note here that the browser will scroll whatever element it needs to in order to show that element, so if you did something special like a scrollable DIV area within your regular body, that div will be scrolled too.
This is an important reason right here why having ID's be absolutely unique is important. So your browser knows where to scroll!
Elements can have BOTH
There is nothing stopping you from having both an ID and a Class on a single element. In fact, it is often a very good idea. Take for example the default markup for a WordPress comment list item:
<li id="comment-27299" class="item">
It has a class applied to it that you may want for styling all comments on the page, but it also has a unique ID value (dynamically generated by WordPress, nicely enough). This ID value is useful for direct linking. Now I can link directly do a particular comment on a particular page easily.
CAUTION: Be aware, Javascript does care
JavaScript people are already probably more in tune with the differences between classes and ID's. JavaScript depends on there being only one page element with any particular, or else the commonly used getElementById function wouldn't be dependable. For those familiar with jQuery, you know how easy it is to add and remove classes to page elements. It is a native and built in function of jQuery. Notice how no such function exists for ID's. It is not the responsibility of JavaScript to manipulate these values, it would cause more problems than it would be worth.
If you don't need them, don't use them
As you can see, classes and ID's are very important and we rely on them every day to do the styling and page manipulation that we need to do. However, you should use them judiciously and semantically.
This means avoiding things like this:
CSS-Tricks.com
We already know this element is a link, it's an anchor element! No particular need here to apply a class, as we can already apply styling via its tag.
Also avoid this:
<div id="right-col">
ID is appropriately used here as the page will likely only have a single right column, but the name is inappropriate. Try and describe the context of the element, not where it is or what it looks like. An ID here of "sidebar" would be more appropriate.
The choice will depend on how your HTML is structured. If a certain style is used more than once, use classes. If a style used only for a specific tag, use IDs. Regarding the selectors, the trick is to keep them as short as possible.
Classes should be used when you're styling multiple elements on a page or across your website such as all the p tags. ID's should only be used once per page to style general layout such as a wrapper, container etc.
Use IDs for unique elements and use classes to apply styles more generally.
Forms should use IDs because generally they are all unique. Anything within that can use classes and you can combine the ID and class to specifically target them if need be.
HTML:
<form id="member-signup">
<div class="align-left">
<input type="text" class="large" />
</div>
</form>
CSS:
#member-signup {
width:600px;
float:left
}
.align-left {
text-align:left;
float:left;
}
input.large {
width:300px;
}
#member-signup input.large {
width:450px;
}
With the semantics of HTML5, selectors are the natural way to go initially for layout based styling.
Classes are great for adding flair to elements and minimal "logic flags" for templates.
Save ids for your special elements like scrim overlays, page names and wrappers.
There should only be one instance of an id on a page, ever; which you should always keep in mind when you are writing code generated markup. Multiple ids per page can lead to some nasty bugs later on; simple bugs, but sometimes difficult to discover.
I didn't see anything on here about it with a quick search, if there is let me know.
Here is an example of a CSS selector I'd write.
div#container div#h h1 { /* styles */ }
div#container div#h ul#navi { /* styles */ }
div#container div#h ul#navi li.selected { /* styles */ }
I write all my CSS like. This allows me to stop from having styles floating around and I can technically re-use the same class name easily. For instance, I might use .selected on multiple elements across the site.
I also specify the element type (div, ul, etc) before the class/id unless the style is used for multiple elements. I also specify the element before id's even though there will only ever be one id because it allows me to know the element easily when reading my CSS. For instance I'll know right off the bat that em#example will most likely have a font-style of italic.
This isn't a question about CSS formating, it's about writing selectors.
I'd love to hear opinions on this approach, as I've used it for years and I'm reevaluating my stying.
Although it's somewhat off topic I also write my selectors like this for selector libraries (like jQuery for instance). Although I haven't looked into jQuery's internals to see if there is performance issue with specifying the element with an ID.
I think it really depends on what the selector is for.
Almost every site has one or a few style sheets that "skin" the site - fonts, text colour, link colour/hover, line spacing, and so on, and you don't want these selectors to be very specific. Similarly, if you have a component or element that's reused in many pages and always needs to look the same - like let's say the tags right here on SO - then it's going to be a pain to maintain if you use selectors based on the ID.
I would always use the ID in the selector if it refers to a specific element on a specific page. Nothing's more frustrating than trying to figure out why your rules don't seem to be working because of a conflict with some other rule, which can happen a lot if everything is classes. On the other hand, I think that nesting the IDs as you are (#container #h) is redundant, because the purpose of an ID is to be unique. If you have more than one element with the same ID on the same page then you can end up with all sorts of problems.
It does make the CSS slightly easier to understand when your selectors provide some idea of the "structure" that's being represented, but, to be honest, I think that goes against the idea of separation of concerns. The #navi might be moved outside the #h for perfectly legitimate reasons, and now somebody has to update the style sheet for #navi, even though nothing about it has changed.
A bit subjective as Darrell pointed out but that's my two cents.
While the question is a little subjective I have to say I agree with your thinking. I think defining the element before the selector is clearer when reading the code and it is less error prone.
I know others have asked about using class and id in CSS files, such as
Div: Class vs Id
So I'm aware of the semantic and syntactic differences between class and id: that id should be used for elements that are used only once and class should be used for elements that share attributes in common.
But this isn't a hard-and-fast rule, is it? What's the harm in using an id for more than one element? Or using a class for only one? After all, isn't "one element" just a set (class) with only one thing in it?
Will the browser's CSS interpreter throw an error if I break the rules? I haven't seen it happen.
So why do we have both id and class? Why not just one one or the other and call it good?
duplicate IDs are not allowed; though your browser may or may not care, the notion makes no sense - how can it be an ID if there are duplicates? ;-)
CSS won't complain if you do it but Javascript sure will if you want to grab one element by its id.
The real answer is that there is a semantic difference between an identifier for one and only one object and an identifier that can apply to multiple objects. While you can break the rules it is best not to.
There is also one other distinction between the two, an (X)HTML element allows more than one class to be applied like this:
<div class="foo bar"></div>
You can't do that with ids.
In answer to the question 'why do we use both classes and ids for CSS, when you're allowed to have a single instance of a class?', look at it this way.
We don't need IDs for CSS. We could just use single instances of classes.
But we need IDs for JavaScript. So, why not use them in CSS too?
Imagine a world in which IDs were there, but only used for JavaScript.
You'd have to code like this:
<div id="wrapper" class="wrapper">
<div id="nav" class="nav">
</div>
</div>
and so on.
CSS is not the problem (you just define styles in there), but the document validity.
An id is meant to uniquely identify an element (for whatever purposes you will be using it) so when you have two elements with the same ID no good things will come.
Remember, the "id" attribute is not meant specifically for CSS styling (not as a class, at least), but for other things - specially JavaScript!
I for one wouldn't use "document.getElementById()" if i didn't know what i was going to get in return...
If you have only one element in a given class you're not doing any harm. The difference is only semantic in this case, as all you are doing is simulating an id. However, if you have more than one element with the same id, you'll have problems with page validation, CSS positioning, and Javascript references to that id. It's best to use id and class attributes as they were intended, for the greatest flexibility in styling your page. Remember, you can have an element with a unique id and have it belong to one or more classes at the same time.
IDs are usefull for elements you know will be unique to each page.
For instance:
a menu (#menu)
the central column where you'll put your main content (#content)
the right column where you put external links (#external-links)
You will probably need very specific rules for these elements (precise, non-relative width & position).
Now each of these elements will contain several instances of a certain type of object:
menu will contain .menu-items
central will contain .articles
external-links will contain .external-link
This subelements are not unique but their layout properties are... thus the use of classes.
And each of these subelements probably have subclasses (like .featured-article) or even some may have an ID (#current-menu-item).
Of course, you can always use classes inplace of IDs but I think using IDs makes it clear about which elements are unique and which are not. Beside, I prefer to have less space-separated names in my class attributes for them to be reasonably readable.
There are many things to say about it. You already know about the semantic meaning of id an class, so I just talk about one case - excluding javascript - when to use an id makes difference: you can refer to elements with an id to navigate inside the page with anchors or from external links: you can link a specific element of an html document with <a href="http://www.site.com/home.html#news> if you want to go directly to the element with id="news". Obviously, you can't to it with classes, because classes are not unique. So, for this and other reasons, is important to have an attribute that identifies an element inside a document.