Class and ID Usage - html

After carefully scrutinizing multiple sources on the Internet, I've discovered that the relatively universal answer to the popular "classes vs ids" question is that ID's are unique identifiers, and an element can only have one ID and that each page can have only one element with that ID. And that classes are not unique, and can be used on multiple elements rather than a single one, and elements can have multiple classes. After concluding with this information, I've begun looking at the source code of popular websites such as CNN, Yahoo, W3Schools, etc. and have noticed that parts of a website that are only used one time still have classes. For example, logos of a website will be under a class, or even a navigation bar will be specified with a class, why is this if there is only one logo on the website or one navigation bar? Wouldn't it be more appropriate to utilize ID's for this matter? This question may seem silly to more experienced developers, but I hope to find some clarification in the answers. Thank you so much.

Classes and IDs are not mutually exclusive. Classes are primarily for CSS styling, while IDs can be for styling, but that's not the reason we generally add them initially. We add IDs so that the element(s) can be more easily accessed via JavaScript and manipulated dynamically.
Therefore it is very common to find elements with both an id and classes - - Each serving a different purpose.

Related

Should HTML IDs be unique throughout the website?

Suppose I am creating a website having 5 pages. If a specific ID is used in one page, can I use the same ID in another page?
Yes, you can, and you should, if you’re using the ID for the “same” element.
Its purpose is to identify the element when linking (using a fragment identifier), scripting, or styling (with CSS).
https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id
You can link to an element with the fragment identifier like https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id#browser_compatibility
If this element is repeated on each site, it should have the same fragment identifier.
If you want to style the element by means of its ID, it absolutely needs the same ID across all pages as well.
On a side note, styling by means of IDs is discouraged because it’s hard to maintain in bigger systems.
The main thing is that it should be a single ID per page, and the number of pages is not important.
Yes, you can use the same id on different pages, since they aren't related to each other.
Applying the same ID to multiple elements is generally considered bad practice since it defies the W3C spec. If you want to style elements across multiple pages, consider using a class.

Should I use a class even for a single html element? [closed]

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 6 years ago.
Improve this question
I am working on a website design and my boss told me that usually ids are never used and classes are preferred, but he doesn't remember why. So I did some research and I found this this, but the first answer does not explain very well why ids should not be used. I thought that for an element that is used only once ids were used. If I won't use an element more than once, why should I use a class?
That's related to performance issues. Even though you are using this element for a single time, I would still recommend using a class instead of an id.
Why? 'cause you may add some more classes to this element in the future. But why is this important and related to performance? Take a look at this:
It’s a common belief that ID selectors are the fastest, but this comes
with a big caveat: IDs are fastest CSS selector only if they’re the
key selector. What’s that? Well, while you probably read selectors
from left to right, browsers read them from right to left.
For more details, just check this site.
I would prefer to use classes. Even if it's a single element. Consider what will happen if you want to reuse the CSS for that single element in the future - it will no longer be a single element and you will have to change it to be a class.
Also IDs have additional functionality compared to classes: you can add the #yourId to the URL and make the browser auto-scroll to that element when you open the URL.
Well if you want to use ids or classes entirely depends on your need. Its not good to say that we should not use ids. Here are some key points.
IDS and classes act as hook and they are required to select an element.
Each element can have only 1 id and each page can have that id only once.
You can use the same class on multiple elements.
You can use multiple classes on the same element. Adding a class name
or ID to an element does nothing to that element by default.
ID's have special browser functionality. 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.
Javascript love ids thats why we have document.getElementById();
Jquery loves classes and its very easy to add classes on an element.
Read https://css-tricks.com/the-difference-between-id-and-class/ for more
class is used to classify a group of elements that can be styled together.
So if you are classifying based on any criteria as per your presentation logic, use classes.
id is used to identify a single element using a unique identifier. So if you are uniquely identifying an element in a page use Ids. The validations make sure its following this concept and throws an error otherwise. So as per specification and implementation there is no reliable way we can use class to uniquely identify an element. Which explains why we are having Id.
As a matter of fact, if you have no need to uniquely identify an element in your presentation, you probably don't require this feature at all.
And about performance, think of performance only when its crucial. Don't over optimise and lose readability and semantics unless performance is already affecting your page rendering.

Why is there such a thing as an id if you can just have classes with only one element? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
From a language-design standpoint, what's the point of creating the id attribute for HTML if you can have a class with only one element? Why not just use classes for everything and not complicate the markup?
I can think of three possible explanations, but they don't fully satisfy me, so I wondered if you know why id was included in HTML. My thoughts are:
The existence of an id helps in creating CSS styles because its greater specificity makes it possible to give an id to one member of a class overriding styles given to other members of that class. This explanation doesn't fully satisfy me because you could just give it an extra class instead and put the styles for that class at the bottom of the stylesheet in a section for styles given to single elements.
When selecting elements with jQuery, the DOM traversal could stop as soon as the element with that id is found. Thus, the existence of an id would make the selection run faster. This explanation doesn't satisfy me because I'm fairly certain that jQuery was created long after ids and classes already existed.
Having an id as a language feature could help to ensure that styles (and selectors) which are supposed to be unique truly are applied to only one element because things go haywire when this isn't the case. This explanation doesn't satisfy me because having your site break when you accidentally create two elements with the same id doesn't seem to be a particularly effective way of informing you that something's gone wrong.
The first publicly available description of HTML was a document called "HTML Tags", first mentioned on the Internet by Berners-Lee in late 1991.
There is a description of anchor tag:
<A NAME=xxx HREF=XXX> ... </A>
HREF
...This allows for the form HREF=#identifier to
refer to another anchor in the same document.
NAME
The attribute NAME allows the anchor to be the destination of a link.
I think NAME attribute here is the predecessor of element's ID: it allowed you to link directly to a desired part of a hypertext page (even if it is the same page).
IDs are unique values so, when you parse the html with something such as javascript, you can be sure of what element your script will hit.
For Javascript anyway getElementById is a few times faster than getElementsByClassName
Test Ops/sec
getElementById 269,235
getElementsByClassName 86,369
ref
More info from the spec
What makes attributes of type ID special is that no two such attributes can
have the same value in a conformant document, regardless of the type of the
elements that carry them; whatever the document language, an ID typed
attribute can be used to uniquely identify its element.
So it is a way to uniquely identify an element, where the class selector could only do so by coincidence.
ref
There are a great many reasons, most of which don't even involve CSS. For example, ajax and JS libraries often require unique IDs, and IDs can act as anchors with URL hashes.
XML is derived from HTML, but used for more generic data. In XML it is very often desirable to have a unique id (the same way it is often necessary in a database). Because XML puts a lot of effort into automated verifiability, the best approach was to simply add the id attribute as a language element. This way, a XML verifier can output an error if the same value is assigned to two id attributes.
Later, many XML features found their way back to HTML, and I guess id is just one of them. It is not strictly needed, but a nice thing to have in combination with Java Script.

Class vs. ID - Readability [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 11 years ago.
What is the preferred method when dealing with choosing a class vs. an ID?
For instance, you can have a bunch of elements that might be styled identically and could all use the same class. However, for readability purposes, it's sometimes nice to have a unique ID for each element instead.
Obviously you don't want to go ridiculously overboard where every element has an ID. However, where do you guys draw the line and does using all IDs where you could be using classes slow things down noticeably? If so... when?
How to stop obliterating semantic HTML.
Most people learn HTML from looking at source code and of HTML and tinkering with it, learning how <tag>foo</tag> looks and running along with it. They don't really gain a deep understand of it, but they go on to do things that require a deep understanding, the side effect is the problem you and thousands of others have every day -- they're doing things and they don't know fully how these tools work, because it looks so simple on the surface and the powerful uses are are "hidden" in the funny manual that nobody feels the need to read. Everything is plainly explained and been written down for a long time.
What IDs are for (directly from the HTML4 spec, with my notes)
The id attribute assigns a unique identifier to an element (it only happens ONCE, never TWICE or more, I'm tired of seeing people come on this site and dropping in their code with the same ID in twenty elements)
The id attribute has several roles in HTML:
As a style sheet selector. (This means, you can use it to describe CSS styles)
As a target anchor for hypertext links.(When you can jump to a section of a page)
As a means to reference a particular element from a script.(document.getElementById("whatever"))
As the name of a declared OBJECT element.
For general purpose processing by user agents (e.g. for identifying fields when extracting data from HTML pages into a database, translating HTML documents into other formats, etc.).
What Classes are for (directly from the HTML4 spec, with my notes)
The class attribute [...] assigns one or more class names to an element (this one gets to be re-used to your heart's content) ; the element may be said to belong to these classes. A class name may be shared by several element instances. The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style information to a set of elements).
For general purpose processing by user agents. (Basically, it's just another part of an element)
What? I don't get it.
IDs: It's the fingerprint of something, there's only one, you only use each fingerprint once in the entire document. You only use it when you need to give something an ID. You probably don't want to have hundreds of these, or even tens of these. You rarely if ever need to start making these. The specific uses are for target anchors, improving selector speed in rare edge-cases. Generally you never describe your CSS based on IDs, you might have some edge-cases such as #HEADER .body h1, which may be different from your #BODY, I'd still advise against making them IDs for no real reason.
Classes: Nothing to do with unique fingerprints or linking to sections of a page, classes don't uniquely identify something. Classes describe a group of things that belong together or should behave the same way. If you're part of the class called coffee you should exhibit classes as one might expect from coffee, if you're a class of cellphone, then look like a cellphone (don't provide coffee).
But how the heck am I supposed to access the 4th cell in the 6th column of some table, or group of divs or that 20th list item?
This is where people who don't know what HTML is throw their hands up in the air and decide to assign IDs to all the elements. This is a total side-effect of nobody properly explaining to you how HTML works. That's a nice way of saying you didn't RFTM or ask questions early on (user1066982 in this case, did, which is amazing and makes me happy, I'm writing this to point other people to in the future who fail at HTML).
You need to start learning right now. Stop pretending you understand this stuff.
HTML is not a string of text such as <foo><bar>baz</bar>blah<ding/></foo>, sure that's how you write HTML but if that's what you believe it is you do not understand HTML in the browser.
HTML is a document that is structured like XML. HTML documents have a model, that means they aren't flat text. The text-representation of that document is a way your browser can take flat text and turn it into a tree structure. Trees are like arrays, except they aren't just flat elements in an array one-after-another, but rather they nest so one element may point to several other elements.
This below isn't a diagram (stolen from the w3c's spec on the Document Object Model) of how to write HTML text, this is a diagram of how your browser stores it in memory:
Since it's in memory like that, it doesn't mean "Oh crap! I have no way to access the first TD in the second TR of the table body in the table!", it means you simply and plainly explain to your code that there is a child element inside of the table.
JavaScript provides a full DOM API that allows you to access every single node in that DOM tree.
PHP provides a full DOM API that allows you to access every single node in that DOM tree.
C++ has a full DOM API that allows you to access every single node in that DOM tree.
ASP provides a full DOM API that allows you to access every single node in that DOM tree.
EVERYTHING that touches the DOM provides a full DOM API that allows you to access every single node in that DOM tree, with the exception of sub-standard software that throws regular expressions around in a futile attempt at parsing HTML.
Use the API for the DOM to access those nodes based on semantic HTML. Semantic HTML means you have a structure to your HTML that makes sense. Paragraphs go in <p> tags, headings go into heading tags, and so on.
You never, under any circumstances, what-so-ever need to reproduce the DOM API through hacking in values with ID tags because you didn't know you could just say getAllEmentsByTagName("td")[4] to get the fourth element.
If you can grab getAllEmentsByName("td")[4] you don't need to do <td id="id4"> and then later getElementById("id4") because you didn't want learn just one other API call. I dread the day I ever have to maintain a pile of code left behind by someone who felt the need to stick an ID into every element "just to be sure", especially when I need to go back and insert a new element between the fifth and sixth element in a table of thousands (can you imagine replacing EVERY id? Especially when this feature was accounted for over 10 years ago?! Insanity!)
Tl;dr
HTML isn't actually just a pile of text with one way to access it
rtfm, stop pretending you understand it because you can do a handful of things, you're holding yourself back.
Don't shove IDs everywhere, only use them where absolutely required.
Use classes to describe things, not identify things.
?????
Profit.
However, for readability purposes, it's sometimes nice to have a unique ID for each element instead.
This makes absolutely no sense to me. What makes an ID more readable than a class? There's no point assigning unique identifiers to each of a group of related elements if there's no benefit in having identities.
For what it's worth, realize that a single element can have both classes and an ID. If your elements need to be uniquely identified somehow, give them IDs. If multiple elements should be styled identically and are all similar in purpose anyway, use classes. If your elements fit both criteria, give them both attributes, and use each attribute accordingly.
IDs should not be used for styling. Use classes instead. IDs have a very high specificity, and are difficult to override (leading to more IDs, and longer selector chains). Also, IDs are used for JavaScript DOM selection, so if you're using the same IDs in your CSS that you're using in your JavaScript, you've tied the styles to the scripts, and that's bad separation of concerns.
IDs are for JavaScript. Classes are for CSS.
Note: JavaScript and specificity are not the only reasons. Others include fragment identifiers and code reuse. As I say in the comments, there are several smart people who advise against IDs (start there and follow the links)
I use IDs for elements that have clear responsibility, Classes for element that have same presentations, for example:
HTML:
<div id='sport-news'>
<article class='news'>...</article>
<article class='news'>...</article>
</div>
CSS:
.news { /* global styles */ }
[id=sport-news] .news { /* specific styles */ }
JavaScript:
var sportNews = document.getElementById('sport-news') // faster
, news = sportNews.childNodes;
For me, [id] .class is more readable than .parent-class .child-class.
When designing, I will use both id's and classes. For specific items I will use id only. But if you need to apply same styles for different items, use classes. You cannot use same id for different items because id is specific to one item only.

Big development teams can't handle a single CSS style sheet?

I am currently in a 5-7 large development team creating a really large website with lots of pages and features.
I feel like we are in such a situation where a developer can change the style sheet to suit his own needs, but is unaware of the 1000 places where it probably change it for something else. I cannot blame him either, since I know it's hard to check everything.
It's a total mess.
I know that using one single style sheet file saves bandwidth and prevents duplicated code and maintenance, but I cant help wondering - is using style sheets a good idea for big sites, or should it be more object/element oriented.
Let's say you forget about the crazy large CSS and you define the CSS on each element instead. So each time you render a GreenBuyButton, it has the "style='bla bla bla'" on it. And this is pretty much done for all elements.
This will increase the bandwidth, but it will not create duplicated code.
Could this be a good idea or how does really large teams work on a single website do with CSS to avoid it being a mess?
Why don't you create multiple CSS sheets depending on the area of the site?
blog.css
accounts.css
shopping.css
Then you could have a serverside script (say PHP) combine all CSS into 1 sheet which will get you the same result of 1 small file (could use a minimizer as well).
Check your overall site with a CSS checker to find duplicates (css defined) and manage it that way.
Otherwise communication is key between your team, who develops what, and so people don't duplicate CSS definitions. A master CSS keeper would be best suited to manage the CSS styles, besides your team should have an agreed upon style and not go rouge creating their own unique styles.
My recommendation would be to use the CSS rules on specifity to help you. For each CSS that is not global, put an activate selector on, for example
.user-list .p {
font-size: 11pt
}
.login-screen .p {
font-size: 12pt
}
This will make it easy to identify what rules are for which pages, and which rules are global. That way developers can stick to their own set of styles, and no mess up anyone else's.
Change how you write CSS.
Instead fo treating every area of the website like a specific piece of markup that needs styling, start defining broad classes.
Enforce some rules. Like, "All <ul> have a specific look for this project." If there are multiple ways you want to style an element, start using classes. This will keep your website looking uniform throughout. Uniformity reduces broken layout.
Create building block classes like a "framework" of sorts. This has helped me so often that I never start a project without doing this first. Take a look at the jquery-ui themeroller framework to give you the idea. Here's an example:
.icon { display:block;width:16px;height:16px;}
.icon-green { background:url(/green.png);}
.icon-blue { background:url(/blue.png);}
Then on the elements:
<span class="icon icon-green"></span>
<span class="icon icon-blue"></span>
Breaking your styles up into their building blocks like this and using multiple classes on the element will keep your team members from having to change styles to suit their needs. If a particular styling quirk is not available they can define a new set of classes.
UPDATE:
Here is an example of how I used this method: Movingcost.com. Huge website, multiple different sections and pages, and only 252 lines of uncompressed css. Actually, these days I break things down further than I did on the movingcost project. I probably would have gone through those elements at the bottom of the stylesheet and figured out how to combine some of those into classes.
Multiple CSS files and combine in code
While doing development I found out that doing it the following way seems to be reasonable and well suited to development teams:
Don't put any styling into HTML. Maintainability as well as lots of head scratching why certain things don't display as expected will be really bad.
Have one (or few of them) global CSS that defines styles for global parts. Usually defines everything in template/master. Can be bound to master page or to generic controls used on majority of pages.
Have per-page/per-control CSS files when they are actually needed. Most of the pages won't need them, but developers can write them
Have these files well structured in folders
use naming and formatting guidelines so everyone will be able to write/read code
Write server side code taht will combine multiple CSS files into a single one to save bandwith.
You can as well automate some other tasks like auto adding per-page CSS files if they're named the same as pages themselves.
Doing it this way will make it easier to develop, since single CSS files will be easier to handle due to less content and you will have less code merging conflicts, because users will be working on separate functionality most of the time.
But there's not feasible way of automating CSS unit tests that would make sure that changing an existing CSS setting won't break other parts of your site.
My favorite override trick is to assign the id attribute on the <body> of each page. It's an easy way to make page specific changes without breaking out a separate stylesheet file.
You could have the following html
<body id="home">
<h1>Home</h1>
</body>
<body id="about">
<h1>About</h1>
</body>
And use the following css overrides
h1 {color: black}
#about h1 {color: green}
The home page gets the default css while the about gets overridden.
Using style sheets on large sites is an excellent idea. However, it only really works when you apply your team standards to the style. It makes sense to have a singular template controller that links your style sheet(s). It also makes sense to appoint someone on the team as "keeper of the style" who all changes to the style sheet should go through before making substantive changes.
Once the style standards are agreed upon and defined, then all of the controls in the site should implement the styles defined. This allows developers to get out of the business of coding to style and simply coding to the standard. Inputs are inputs, paragraphs are paragraphs, and floating divs are a headache.
The key is standardization within the team and compliance by all of the developers. I currently lead a team site that has upwards of 30 style sheets to control everything for layout, fonts, data display, popups, menu and custom controls. We do not have any of these issues because the developers very rarely need to edit the style sheet directly because the standards are clearly designed and published.
The answer is in the name. The reason it's called cascading style sheets is because multiple can be combined and there are decent rules defined on which one takes preference.
First of all, doing all your styling inline is a ridiculous idea. Not only will it waste bandwidth like nothing else, it will also result in inconsistency. Think about it for a while: why would changing a line of css 'break' another page? That indicates your css selectors are poorly chosen.
Here are my suggestions:
use one css file for the basic site look. This css file is written by people doing mainly design, and as a result the site has a consistent look. It defines the basic colors, layout and such.
use another css file per 'section'. For instance, a 'shopping' section will use components that are nowhere else on the site. Use that to define section-specific stuff
put page-specific styling directly in the page (in the header). If this section becomes too big, you're doing something wrong
put exceptional styling directly on the components. If you're doing the same thing three times, abstract it out and use a class instead.
choose your classes wisely and use the semantics for naming. 'selectedSalesItem' is good 'greenBold' is bad
if a developer changes a stylerule and it breaks the rest of the site, why did he need to change it? Either it's an exceptional thing for what he's working on (and should be inlined) or it was basically broken on the rest of the site as well, and should be fixed anyway.
If your css files become too big to handle, you can split them up and merge them server-side, if you want.
You don't want to define CSS for each element because if you ever need to make a change that affects many elements one day, say the looks of all the buttons or headers, you will be doing a lot of Search/Replace. And how to check if you forgot to update one rule to keep your site consistent?
Stephen touched on a very strong point in CSS. You can assign multiple classes to an element.
You should define some basic rules that "ordinary" developers can't touch. They will provide the consistency through the site.
Then developers can assign an extra class to personalize any property. I wouldn't assign more than two classes though: a global and a personalized.
Considering you already have this huge stylesheet in your hands, I'm not sure how you will pick which one of the 7 developers will have to sit down through a month and organize it. That is probably going to be hard part.
First off, you need to extract your website's default element styling and page structure into a separate stylesheet. That way people understand changing those rules affects the entire site's appearance/structure, not just the page they're working on.
Once you do that, all you really need to do is document / comment all of your code. A person is a lot less likely to write duplicate code in a well-documented stylesheet, and that is a fact.