CSS: are class and id interchangeable? - css

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.

Related

Difference between id and class [duplicate]

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.

Is it improper to use an ID as a CSS selector? [duplicate]

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.

CSS Best-Practice: Selectors or Classes / IDs? [closed]

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.

css selecting a lot of ids classes

I want to select a lot of different ids and classes. For example:
<div id="a b c d" class="e f g h i j ">Red text</div>
#a.#b.#c.#d.e.f.g.h.i.j{color:red;}
Also tried:
#a#b#c#d.e.f.g.h.i.j{color:red;}
JSFIDDLE: http://jsfiddle.net/vHvm9/
This doesn't work. Doesn't CSS support that much selection or am I doing something wrong?
As far as CSS is concerned, your second selector #a#b#c#d.e.f.g.h.i.j is valid and you could theoretically match an element with multiple IDs in CSS. But this will only work if the DOM actually allows an element to have that many IDs in the first place. In HTML, spaces don't separate ID names like they do class names; an HTML element can have only at most one ID specified by an id attribute, and that ID isn't supposed to contain spaces (even though a browser will happily take it if you feed it such bad markup anyway).
You can still assign other IDs to a single element by other means (again, if the DOM allows it), but there is absolutely no practical reason to unless you're working with some obscure markup language where having multiple IDs means something.
So, to answer your question: what you're doing wrong is attempting to assign multiple IDs to an element at all. Just assign one ID without any whitespace in its value, and select by that ID.
As Jan pointed out single element cannot have multiple IDs in HTML or XML.
But if you will find host language (for CSS) that supports multiple IDs then you should use correct CSS selector:
#a#b#c#d.e.f.g.h.i.j{color:red;}

ID works same as CLASS

I know that ids are for single elements and class is used for multiple elements on the same page. But then why ID styling is applied when there are multiple same ids?
http://jsfiddle.net/WqrAF/
Now, it works then what's the difference?
You cannot select a single id if there are many of it. You will run into problems when you need just one instance of a dom object.
That's because browser try very hard with invalid and malformed markup. They don't always succeed to do what the author intended though.
The solution is to always write valid markup, and check the validation.
This is just the browser coping with invalid HTML. There should never be more than one instance of the id attribute with the same value on one page.
The main difference: for ID, it should not appear in the same HTML more than once; for class, it can be used many times in same HTML.
The behaviour is undefined when you use invalid markup. All major browsers may be able to correct your wrong markup but you cannot rely on that.
Another difference is that ID-Selectors are more specific than Class-Selectors:
inline style
ID
classes
elements
That means an ID-Selector always wins over any class selector - no matter how many class and element tokens the selector contains. (Unless the class selector styles contain !important. But that's about CSS-Importance and not CSS-Specificity then. This is because CSS-Importance takes place before CSS-Specificity is considered.)

Resources