CSS Class & ID Structure / Naming - html

I am a web developer for almost 2 years now and I am still learning new things every day, but since my knowledge gets bigger, I came across some fundamental question and couldnt find a good discussion about it.
How do you name your DIVs, IDs, Classes? Do you give them specific content related names? (i.e. <div id="google_map">)
Or do you name them related to their position on the site? (i.e. <div id="content_top_bar">)
And do you do this in your .css the same way?
I hope you get what i am trying to find out. I guess there is no "true" answer anyways, but I would like to know some opinions, so that I can decide what option to take and keep working with it in the future.

HTML should be used as semantically as possible, so your classes and IDs should be named for their content, not for their style, or their position within the site (these things should be able to change without effecting your HTML.
For example, if you name a <div id="left-sidebar"> and then later decide you'd like to move that element, the id no longer would semantically represent the element. Conversely, if you named a <div id="navigation"> or <div id="article"> they would still represent the element, regardless of their placement or styling on the page.

I would name objects based on their content (whether logical of physical). You care what an object is not where it's at.
The exception to the above rule is when the object forms the layout of the page, but in that case it shouldn't really have a name anyway, unless you intend to manipulate the structure of the page to move stuff around at run-time (which is fine, just rare).
Also I find myself not naming a lot of objects anyway, but assigning them classes, especially for related objects that I have to manipulate together. It makes working with them through jQuery (or whatever framework you choose) a lot easier.

I think there is a definite answer to this question: Whatever works best for you :)
Some things to consider:
Are you the only one writing in the codefiles or not?
What's the structure of your site and is it static or dynamic?
Depending on these you may opt to choose english names or your own language, or you may opt to name a div "content" rather than for instance "div_homepage".
Hope that was helpful :)

Since HTML is for content, your naming should refer to content.

Depending on what the html element represents:
The element is part of the layout, name it to something that represents that part of the layout.
example: 'footer_top_bar'
The element is used for specific content, name it to something that represents the content.
example: 'comment', 'navigation', 'breadcrumbs'.

Related

Why are most elements assigned to a class instead of an ID? [duplicate]

This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 8 years ago.
Lately I'm working with a lot of Wordpress themes. When I have to edit a particular element, I usually use Firebug to see the element's name so I can change the CSS. I think I understand the difference between IDs and Classes, Classes are used for a group of elements that you want to share the same styling, and ID is usually used for a single element.
Here's the thing, I'm seeing so many elements in these Wordpress themes that are only used once, but they are assigned to a class. A good example is the website logo. Isn't the logo only used once? Shouldn't it be assigned to an ID? Why is it always assigned to a class?
Needs change often. An element/style that today you think will only be used once may be used multiple times in the future. Maybe you will have your logo more than one time on your site (for example, on your about us page). Perhaps you may eventually incorporate a second search bar. There are very few cases where you know with 100% certainty that the style will only be needed once.
Here's a good read on the subject: http://oli.jp/2011/ids/
http://ryanfait.com/articles/the-difference-between-ids-and-classes/
Ryan says
"I take a different stance than most web designers when it comes to
using ID's and classes. The vast majority of CSS coders use ID's for
any elements that are simply used once on a page. However, I only use
classes to style my websites, but, when I want to use an element in
JavaScript, I use an identifier. From a presentational standpoint,
styling elements with classes looks exactly the same as styling them
with ID's, but the flexibility of classes offers a certain appeal even
if I don't plan on using a class more than once on a page. Also, when
I see an ID in my XHTML, it reminds me that there is some JavaScript
that refers to that element. It's up to you, but so long as you
implement classes and ID's properly, it is more or less a matter of
personal choice when to utilize one or the other."
id is a unique one, but when class its not, you can you one for many selectors
ID's are unique
Each element can have only one ID
Each page can have only one element with that ID
Classes are NOT unique
You can use the same class on multiple elements.
You can use multiple classes on the same element.
Any styling information that needs to be applied to multiple objects
on a page should be done with a class. Take for example a page with multiple "widgets":
There are some reasons why people prefer using classes instead of id's in CSS. (note that for javascript ID's are still commonly used).
The class element is re-usable on that page. This means that you won't have as much duplicated code with Classes as you would have with ID's.
Usually, IDs refer to something very specific, and abstracting would be tough
Any performance gains picked up by using id, is negated by adding any other selector to the left fo that id. Which mainly means that in most uses of id's you won't really have performance gains. (you could even have less performance than if you would just use a class)
Lecture about this:
http://screwlewse.com/2010/07/dont-use-id-selectors-in-css/
http://www.impressivewebs.com/css-specificity-irrelevant/
http://www.baldurbjarnason.com/notes/ids-in-css/
If you're new to web development, just use the simple rule:
If you're trying to apply style to a HTML element, use a class.
If you're trying to interact with a HTML element with javascript, use an ID.
You see more of classes because they can be reused and assigned to multiple elements.
However an id can belong to only one element at a time hence less of them.
Classes only appearing once:
Such cases like the one you identified, you may call them semantically incorrect as id is more appropriate choice for that but still it would work and it probably happens couple of times that we get to use class which only appearing once (may be while defining that class we are thinking that we can use it somewhere also but at the end we really dont), beside general habit another reason could be:
That class styling is also used somewhere else along with another class for e.g.:
.logo{
width:250px;
height:250px;
float:left;
}
.logo class is applied to logo <div class='logo'>...</div> But there is another element which also require same three properties of logo and some other also so one can reuse logo there also.
<div class='otherstyle logo'>...</div> this would apply the style of logo as well as otherstyle to it.
In some other words to sum it up. The cardinality of a class is 1...* so you can use it one and more than one time. But for id it is 1...1 you will and only use it only once.

Should css class names like 'floatleft' that directly describe the attached style be avoided?

Lots of websites use class names like floatleft, clearfloat, alignright, small, center etc that describe the style that is attached to the class. This seems to make sense so when writing new content you can easily wrap (for example) <div class="clearfloat">...</div> around your element to make it behave the way you want.
My question is, doesn't this style of naming classes go against the idea of separating content from presentation? Putting class="floatleft" on an element is clearly putting presentation information into the HTML document.
Should class names like this that directly describe the attached style be avoided, and if so what alternative is there?
To clarify, this isn't just a question of what to name classes. For example a semantically accurate document might look something like:
<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...
<div class="foobar">Another unrelated topic</div>
Say all these divs need to clear floats, the css would look something like:
div.foo, div.bar, div.foobar {
clear:both;
}
This starts to get ugly as the number of these clearing elements increases - whereas a single class="clearfloat" would serve the same purpose. Is it recommended to group elements based on the attached styles to avoid repetition in the CSS, even if this means presentational information creeps into the HTML?
Update: Thanks for all the answers. The general consensus seems to be to avoid these class names in favour of semantic names, or at least use them sparingly provided they don't hinder maintenance. I think the important thing is that changes in the layout should not require excessive changes to the markup (although a few people said minor changes are okay if it makes overall maintenance easier). Thanks to those who suggested other methods to keep CSS code smaller as well.
It's great until you re-design, and narrow is highlighted yellow, center converts better left-justified, and the image you called floatleft now belongs on the right.
I'll admit to the sin of using floatleft and clear as CSS class names, but it is much easier to maintain your CSS if you choose names that relate to the semantic meaning of the content, like feedback and heroimage.
Presentational class names
The HTML spec is clear on this issue:
There are no additional restrictions
on the tokens authors can use in the
class attribute, but authors are
encouraged to use values that describe
the nature of the content, rather than
values that describe the desired
presentation of the content.
Does clearleft describe the nature of the content? Not really. Eric Meyer made a joke about this a while ago.
Try to find a structural relation between the seemingly unrelated elements
Let's say you have paragraphs about ducks, paragraphs about monkeys and paragraphs about frogs. You want them have a blue background.
<p class="duck"></p>
<p class="monkey"></p>
<p class="frog"></p>
You could add this CSS rule:
p.duck, p.monkey, p.frog {
background-color: blue;
}
But aren't they all animals? Just add another animal token:
<p class="animal duck"></p>
<p class="animal monkey"></p>
<p class="animal frog"></p>
And change the CSS rule to:
p.animal {
background-color: blue;
}
It is hard and it might not always be possible but the important thing is not to give up quickly.
What if you can't?
If you have a lot of elements with absolutely no structural relation between them, that indicates a structural problem with your document. Try to decrease these elements. That said, grouping n CSS selectors on one rule is still better than adding n presentational class tokens in your HTML document.
Style classes should be semantic. This is a great article on semantic web page design (well, I found it really helpful anyway).
EDIT: I just read another article that makes some good points for using things like display: inline-block, display: table etc. instead of floats. That should help avoid those pesky floatleft and clearfix classes. Making them semantic is always up to you though.
The main problem with having classes named floatleft, clear or the like is the fact that changes in the design imply changes in the HTML markup. This should not happen, true separation between content and presentation is achieved only when you can re-use the same markup in multiple designs or even media (think sharing the same HTML between desktop and mobile versions of your site and only switching sylesheets).
Now, for a practical example :). To add on Fredrik's answer, LESSCSS allow you to hide styles declarations/mixins from developers. This way you can protect reusable components in your stylesheets without the danger of having them pop up in your HTML.
Sample markup:
<div class="branding">Company Name</div>
Sample less code:
// example of reusable functions
.noText() {
color: transparent;
text-indent: -9999px;
}
.clear-after() {
&:after {
content: ".";
display: block;
visibility: hidden;
height: 0;
clear: both;
}
}
.branding {
.clear-after();
.noText();
background-image: ...;
}
Of course, for mobile you might just want to have the company name in bold, without any other styling:
.branding {
color: pink;
font-weight: bold;
}
I think it depends on how you are using the styles.
Content should be named accordingly, as the style may change but the content will likely remain the same.
For instance, if you have a div that contains stock info, you should name the div something like div class="stockInfo", so that no matter what the presentation, you can change the styles and the name will not contradict those styles (as opposed to naming the div div class="yellow" and then changing the background-color to red).
However you will have "helper styles" and these should be named for what they do.
For instance, you will likely want to use a <br /> to clear some floats. In this case, it is perfectly reasonable to name it <br class="clear" /> and to give it a style of br {clear:both;}.
Again, most Web sites float their images right or left. To assist with this, you can set <img class="right" src="" /> and <img class="left" src="" /> and then have the styles to match, img.right {float:right;} etc.
So it depends on the usage.
Class names and ids that describe the function is better than using names that describe the styling of the element.
I usually end up not doing it religiously though, because it is in my opinion more convenient to i.e. clear floating elements by using the famous clearfix hack rather than adding clear:both all over the stylesheets.
But I think that LESS and SASS creates interesting opportunities to get the best out of both worlds, because you can have mixins and functions that describes some style and still have semantic correct names by just including whatever 'style' you want.
Instead of having this HTML and CSS
<div class="navigation roundedcorners">...</div>
.roundedcorners {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
you could use SASS to create this mixin:
=rounded-corners
-moz-border-radius: 5px
-webkit-border-radius: 5px
border-radius: 5px
and include it into your .navigation class like this:
.navigation
+rounded-corners-5px
which would reduce your HTML to this:
<div class="navigation">...</div>
and therefore still get the advantage of having semantic correct names while having a convenient way to share styles between different elements.
Andrew; it's good to give sensible name to an class & id which easy to understand for you & your fellow member's which are working on that project. For me classes small , center , floatleft etc define nothing to me because when you give class center that's indicate that the element on the center but there are other properties also in that class like color, background etc
For example
<div class="wrap">
<div class="center">lorem</div>
</div>
css:
.center{margin:0 auto;}
in this example class center don't clear to me. but we can use them as a helper class.
For example
<div class="wrap">
<div class="panel center narrow">lorem</div>
</div>
css:
.center{margin:0 auto;}
from above example now it clear to me what the role of class center in that panel div
FOR MORE CHECK THESE LINKS :
What's the best way to name IDs and classes in CSS and HTML?
http://www.ronniesan.com/blog/entry.php?title=organizing-your-dom-elements-with-the-proper-ids
http://cssglobe.com/post/3745/my-top-10-most-used-css-class-names
If your question is:
Is it recommended to group elements
based on the attached styles to avoid
repetition in the CSS, even if this
means presentational information
creeps into the HTML?
Then my flat answer would be that in real world, semantic and presentation isn't everything. So my answer would be: it depends.
...depends if bandwidth is important to you... On a site with many visitors per hour, then the classnames could even simply be something like "c11" (yes, I've seen it) instead of meaningful, but looong class names.
...depends also if you perfectly know that when the look and feel will change, then the CODE will change also. (exemple: you redesign a site today in XHTML, but you perfectly know that when you'll re-do the CSS in 2 years, then you'll want the markup to be HTML5, so you will pretty much change the structure anyways...)
...depends also if you're already 3 days late on a delivery. When you're 3 days late, believe me, classnames like "nopadding" starts to appear, as you don't have anymore time to think straight about semantic (neither does your client).
Depends on so many things, I'd say... That's my "real life" point of view of your question.
From what I've seen, developers have the tendency to overload their HTML pages with way too many unnecessary classes and extra markup. These classes not only make the page size bigger (and thus the load time longer), they also crowd up the page and make it difficult to manage and modify at a later time.
Having things like center and float-left might be helpful when you're dealing with display text that was input by a user (such as a post on a forum), but for general markup purposes you're better off just adding text-align: center and float: left to the appropriate classes. This especially helps if you are trying to change the appearance of your site without changing the HTML much. The less you have hardcoded into your template, the easier it is to only have to change around the CSS when modifying your template. That bit alone is worth it to me.
As a general rule of thumb, you really should only give elements classes when it describes what the content is, not where or how it is being displayed. i.e. <span class="movie-information"> instead of <span class="bold">.
The only time I feel that it makes sense to give an element a class when it isn't necessary is if you are concerned with Search Engine Optimization. You should definitely read up on Microformats if you are interested in seeing how adding the right classes can actually help search engines. That being said, adding classes that describe how the page is visually displayed does nothing for the search engines.
The only time I would ever "group" classes is if they are either displaying the same thing, or if they are siblings. It gets really messy in your CSS when you have elements from all over your page defined together. You're much better off grouping your classes in your stylesheet in ways that you will be able to find them later, rather than saving a few lines by combining them.
I think this is where old meets new in web technologies. From times past, it has been difficult to unobtrusively render an outstanding web experience. These class names mostly came in handy when websites were changing webmasters to aid them in understanding the code. It served its cause well but with the new technologies of this day and age, I think this is slowly dying out - infact, it should be dead.
The question we should ask is, "Do we need to create a new class for every new innovative design that could pass as a template?". I do not think so. The markup on a site should do what it is meant for - markup. The class names used in the markup should be descriptive of the content and not its looks. The stylesheets - on the other hand - should be able to select elements on a document based on the information in the markup, and style them.
I want to relate this to the Rails association naming convention. Consider this...
class Post < ActiveRecord::Base
has_one :personifyable
has_many :personifications, :through => :personifyable
has_many :taggables
has_many :tags, :through => taggables
belongs_to :destroyers
end
Obviously, this is not a real model; it is something I am using to drive a point. Consider the case of a deeply nested dependency. These names will grow ridiculous - if they aren't already (i.e. in CSS, <div class='mediumwidth floatright centeredtext graytheme master'></div> or something of the like)
Now consider the case where you have different principles. Different developers and designers may - if not 'most definitely will' - have different reasons for using a specific naming convention. How would this affect refactoring time. I will leave that to your imagination. Also, if your business partner notices a new trend with sites themes that attracts traffic - more technically, assume this business partner has performed some experimental A/B testing and come up with some specs - you don't want to change the contents of the whole stack (ie HTML and CSS and possibly JS pages) to implement this new style.
In conclusion, keep styling hints out of your markup. Unobtrusively interact with the document to style and manipulate it. Sass gives you a fine way of styling a site while having your CSS mock your markup. jQuery is another awesome UJS library. HTML5 gives you methods too that make the markup more flexible and yields more information to CSS and JS.
I don't think adding a descriptive class name to your document is really a big issue. I find it's easier to work with explicit class names like "floatleft" as opposed to things that are purely semantic or reliant on the cascade. It's usually easier for later developers who don't have the document structure in their heads as well.
You don't want to use them for everything--you wouldn't want to add a class of floatleft to every li in a left-floated menu, but these kind of styles are very good when you need to do a specific thing to one or more elements, and you want to make other developers aware that you did it.
It's like putting in <div class="clear"> or even <div style="clear:both;">: maybe not the prettiest but it sure is obvious what you are doing.
My rule of thumb is: whatever makes you have to think less, do that.
EDIT: As I said in my comment above, this is most true for classes that refer to clearing and floats, i.e., things that are purely presentational, non-semantic, and yet must be referred to in the HTML. I think in this case it is actually preferable to indicate that you are using a purely presentational class, like floatleft, rather than forcing the float to be attached to some semantic element.
I am a developer before a programmer, so for me I use something like a "floatleft" css class as a sort of UtilityMethod.
Meaning, my css class is "floatleft"...and that's all that class does.
so if I say <div class="floatleft"></div> in my mind that is saying "make this div float to the left".
So if that Div also needs a blue background and is my main header it's going to have a different class for that and I end up with <div class="mainheader floatleft"></div>
Doing it this way also avoids issues with refactoring. If I am changing my design later, I will know that "floatleft" ALWAYS floats things left and nothing more.
I think, at the end of the day it is about what works for you. If your class name is descriptive of what it does, that does not really go against the rule of separating markup from styles. Another factor to consider is, are you the sole developer, or part of a team. If you are part of a team, or you know your code will be worked on later by other devs, you should establish, and document the naming conventions used.
I am currently contracting with Down Jones on some very large projects, and we have a rather lengthy document on naming conventions for our classes, including when to use camel-case, or dashes or underscores, as well as specific prefixes on the class name based on the project we work on. It sounds crazy, but when you have a dozen or so front-end devs working on stuff at the same time, it is a life saver!
You are saying something like this:
.red
{
color:red;
}
so in order to use this class:
<ul>
<li class="red">hello</li>
</li>
ALTERNATIVE SOLUTION
ul li
{
color:red;
}
Usage:
<ul>
<li>Hello</li>
</ul>
By this you can actually remove the presentation information from the content.
I personally name them things close to what they will be doing. Say I have a class that is on an image gallery and its a primary most used class it will be something like "gallery" or if I'm setting borders around things that are meant to be more decorative I'll name it "decoborder". I try to keep them semi short and somewhat related what task they provide. I don't like to do things like "small, large, H1underlined" or anything that can mimick another tag or function because that can just get confusing. Beyond that I think you should really name it in whatever way makes the most sense to you.
If the question is only one of naming, then for one specific class...
class="floatleft"
or
class="myClass"
or
class="gibberish"
....changes absolutely nothing. They are only different class names. The programming functions the same.
Either your content & presentation is separated, or it isn't... totally regardless of how you created the names.
For what it's worth, if I remember correctly the class keyword in HTML isn't currently used for anything other than CSS stylesheets. Thus, the example that you provided...
<div class="foo">Some info about foo</div>
...
<div class="bar">Info about unrelated topic bar</div>
...wouldn't really be a way of identifying data. I would suggest either the name or id attribute if you really want to identify data within your HTML tags. (They both have slightly different uses - name is generally used for server-side queries while id can be styled and is generally more versatile. IDs must be unique, but names don't have to be.) You can check further documentation using the W3C HTML specification.
In short - don't worry about tying content to presentation through your tag classes; until they're specifically used for anything else, they will not have any real effect on your raw content. As such, I'd say name your classes whatever you want, as long as it makes sense. Personally, I would err on the side of logical naming versus style-type naming (e.g. class name "editorcomment" instead of class "graybgfloatleft" or something like that), but in the end, your class names aren't going to tie your data to your presentation like an ID or a name would.
Good luck.
I've done both and I have to say nowdays I lean towards using non presentational classnames. I found this nifty framework called OOCSS https://github.com/stubbornella/oocss/wiki which helped me alot when I was creating a new layout for my web application and suited my requirements so well.
It is mostly because the definition of basic classes for spacing, headers and text works so well when you have to deal with alot of content. Because you use the same classes everywhere it helps make the layout better and maintainable.
Offcourse this means a element in your html can look like this: <div class="unit size1of3 lastUnit"> But isnt that what HTML is about? Making sure your information is presented properly.
I disagree on the whole redesign point, be honest, when you have to redesign your website most CSS goes out the door anyways. And, by dividing the CSS into proper classes for spacing/heading/text it becomes less likely to have conflicting css rules that mess stuff up like ul li div{}
Offcourse the classes do not describe the contents, but as CSS does not allow class inheritance and you have to support old technology like IE6...does it really matter? And do classnames like animal and duck really make for better html? Id like to think HTML is for the browser and when the browser renders it, thats for humans.
It depends, sometimes it makes sense just to add a class to let an element float. The problem with the semantic approach is that you will end up ball of mud of css classes. Sure, names like redLink or blackHeader have to be banned but sometimes you will need little helpers like "clear" or "floatLeft".
Read this article of Nicole Sullivan who explain this in deep.
There are two things that I feel get entirely left out of these discussions all too often. The first is WHY you would want to be all semantic or all not. The keywords are Branding and Skinning. Presentational class names may be justifiable if you work on some internal, departmental websites where branding and skinning will never in a million years get funding. On the other hand, customer facing sites, such as car manufacturers and department stores live in a world where every single new product that gets launched results in an entirely new skin for the website. New colors, new layout, new background images and all of this lead by designers who should be able to make the change purely in css so there's no chance they can break any working php (or what-have-you). There are also branded sites, where you have multiple skins, potentially running on the same site simultaneously. On sites with that requirement, you can't have visual changes impact html or you end up breaking every other brand just to update one of them. In these situations, semantic class names are a necessity.
The second thing that often gets left out is how to combat the problem of repeating groups of properties created by semantic class names, as in:
.content-nav {
float: left;
margin-right: 10px;
background-color: #ccc;
}
.content-nav .user-photo {
float: left;
margin-right: 10px;
border: solid 1px #000;
}
.content-nav .user-display-name {
float: left;
margin-right: 10px;
text-decoration: underline;
}
People often point this out as a drawback of semantic names, and I think that that's a valid point. On the other hand I would like to point out that there are tools that can help you keep semantic css DRY, such as LESS and SASS. I did see one other commenter mention this above, but I just thought that this point was worth highlighting.

Is it okay to use an id for <p> tags?

My coworker is telling me I shouldn't use id's for paragraph tags...
I think it's the way to go if you know you're only using that kind of paragraph once on the page.
He also says that all elements on a page should only use class and not id, unless you are defining a header, container, or footer.
I am fresh out of college and I learned to use id for things that will only show once on a page, while using class for things that will show multiple times on a page.
Which way is proper?
I'd say it's fine as long as you know that the paragraph will only be used once on the page.
An example might be a piece of company info that you want to appear on multiple pages but be styled in a particular way. Giving that an id singles it out as unique and allows you to style it as such.
The class attribute should be used for styling a number of controls in a similar way (i.e. all those that belong to that class). For example, report totals might always need to be large and bold, so the encompassing tags would be given a reportTotals class. There might be more than one report and more than one total per page, but they should all look the same.
Yes, it's OK. Every DOM member can have an ID. There is nothing fundamentally wrong with a <p> tag using an ID.
Now, for applying CSS may be the case that is better for you using a class attribute instead of an id in <p> case because you might want to apply that style to several paragraphs. But it's just a matter of convenience.
From a semantic point of view, I would say that if the ids help split up the document structurally then using ids makes a lot of sense. For instance, you may have:
<p id="beginParagraph" ...> </p> and <p id="endParagraph" ...> </p>
that help easily identify and locate your beginning and ending paragraphs. Keep in mind that you should not have duplicate ids however, and the example above could easily get out of hand if you have many paragraphs and wanted to add an id for each.
Check out this article on Classes on Ids for other reasons why one might be better over another:
http://css-discuss.incutio.com/wiki/Classes_Vs_Ids
Use an id to refer to a specific element. Use class to refer to all elements of a specific type.
I think [you should use id on a paragraph tag] if you know you're only using that kind of paragraph once on the page.
You shouldn't use id just because you only happen have one of them on your page. You should use id when you want to be sure to only affect that one specific element, both now and in the future when other people add more paragraphs. If you have a specific "kind" of paragraph there is nothing wrong with using a class to represent this, even if that class currently only has one member.
I find the use of ids for HTML elements, specifically paragraph tags, is very useful when running automation tests using tools such as Selenium or in my current project that uses AngularJS, when running end-to-end tests using Protractor. It is much easier to make expectations by element ids than using class selectors.
Yes, it is perfectly okay to use the id element for the paragraph element. Just make sure you specify which paragraph if you are using more than one.

What are the side effects of using multiple instances of a single id name in HTML?

Just curious to find out exactly what problems I'll cause myself if I include multiple elements in my web-page with the same id?
for example:
<div id='someID'>Some Content</div>
<div id='someID'>Some Other Content</div>
When you try and reference those elements from JavaScript it won't be able to resolve which element you are referring to. Depending on the specific JavaScript interpreter you are running on, you may either get errors, or undefined behaviour - both cases are undesirable.
The HTML spec states that Id's should be unique, so your HTML will be considered as invalid and may cause browsers to drop back into quirks mode rendering, or even totally refuse to render your page (although that's not likely, and all current browsers will render something - technically, if you don't follow the spec the browser is under no obligation to do anything but reject your page).
You should consider using class names instead if you want something to identify multiple elements by:
<div class="someClass">Some Content</div>
<div class="someClass">Some Other Content</div>
Blair has pointed out in the comments below that if you need to search for elements by class from JavaScript, you can speed the search up by going from the nearest element with an ID and also tell it what node type to look for. This can keep the access speed fast in a lot of cases, but doesn't break any rules on duplicate id's:
HTML:
<div id="myNearestID">
<div class="someClass">Some Content</div>
<div class="someClass">Some Other Content</div>
</div>
JavaScript+JQuery:
$('#myNearestID div.someClass')
IE will have major problems with any javascript using IDs, that's the main side-effect.
Overall, IDs are unique, per the spec...the browser maker is free to make this assumption in their code, and any bugs (Javascript, CSS, etc) that result from invalid HTML involving them...well, that's your problem :)
The browser isn't obligated to fix it really, and I don't think they should either.
I’m not sure how browsers render the CSS rules of type #someID in such case (they will probably apply the rule to all such elements), but you’ll certainly run in trouble with JavaScript and getElementById.
I read elsewhere that IE creates a global variable for each element with an ID.
Am I wrong in saying that's an issue too?
A couple more points not already noted.
Fragment identifiers: How would the browser handle a link to http://www.example.com#someID ?
Internal references : If someID was on two input elements, and you had <label for="someID">... if the user clicked on the label, the browser would have to decide which input should receive focus. (In HTML5, this is defined to be the first input, which is not necessarily what you want). Likewise for ARIA support, some attributes such as aria-labelledby and aria-describedby rely on pointing to a single place.
Then which one control you want to refer when you do something like this in Javascript:-
document.getElementById("someID")
I don't think the browsers will complain, but the other problems you would observe are:
The page might not validate due to dulicate ID declaration
The javascript's which might be running on the page might stop working correctly if they are finding elements by ID since at this time, it will get the wrong element
The CSS rules applied at #ID will be repeated to all the elements which have the same ID
I think these are enough problems to warrant not using the same ID across all elements.
HTH.
Browser will go mad when we are referencing it through JavaScript or somewhere else in code-behind file.

What's the best way to name IDs and classes in CSS and HTML?

When naming classes and IDs for CSS what is the best method to use. In this case I need there to be some kind of naming convention so that other people can pick up rules and understand how to name their own ids and classes using the same pattern. Any suggestions? Some of the sites we create can get pretty complex but use an overall structure header, content and footer. The naming must be efficient too.
I am not new to CSS. I am aware of giving them names that represent their structure etc., but just want to know people opinions really and ways of doing this.
The best advice is to use class with semantics in mind
Good names don't change
Think about why you want something to
look a certain way, and not really
about how it should look. Looks can
always change but the reasons for
giving something a look stay the same.
Good names
warning, important, downloadableImage and submenu are all
good names. They describe what a
certain element represents, and they
are not likely to change. A warning
will always remain a warning, no
matter how much the look of the page
changes.
Bad names
border4px, lighttext and prettybackground are all examples of bad
names. You might fatten that border to
a whopping 5 pixels, or the background
may look pretty old after a while, and
not pretty at all. An advantage of
using CSS is that you won't have to
change much in order to change the
looks of your website. If you have to
change all light text into dark text,
and thus change all classes lighttext
to darktext in all your HTML pages,
you're likely to miss a few.
from this article
IDs can only be used once per page, so they are useful for major structural elements like "header" and "footer" (until HTML5 comes in and replaces those with native elements).
Classes can be used multiple times, and you can use multiple classes per element. They should be kept fairly generic - so instead of, say, warningMessage you could create one style message with the basic layout style, and then warning, info, and error styles with different colours. Then use <div class="message warning">etc</div>
You should also use HTML elements where applicable. Instead of <span class="title">, use a heading tag like <h2>.
As others have said, you can use underscores or hyphens or camel case - i.e. my_style or my-style or myStyle. Just choose a convention and stick to it (personally I use my-style). Jitendra suggested in a comment that lowercase is better when you're using gzip compression, which is true all round - for font names, hex colours, and it's worth naming files (e.g. background images) in lowercase anyway.
Sometimes coming up with good names can be hard. Think about other places you might use the same formatting. For example, if you want to put the author and date of an article below the title in smaller grey text, you might use .authorAndDate, but a better way would be .byline. This is still quite descriptive, and can be used in other places too, say, image captions.
header
footer
container
.post
.title
Those are the ones which come up in most of my projects but obviously it depends what you're doing. Just try to keep it logical.
be descriptive and name your ids and classes in a semantic way, give them meaning
There is no real naming convention. Just agree on one with your team and keep it consistent. For instance don't mix camel case and snake case.
Try to be as description as possible when naming a class. Example:
.menu: bad
.head_menu: better
.wrapper: very bad
.main_content_wrapper: better
edit; Worse naming convention I saw is using the actual content of the styling. For instance:
.redButton
... because when I got to the code (legacy code), but "red button" was not red but blue (or something like that).
Try to use something that will not likely change, like the purpose of the class.
The rules for naming an id or class attribute are simple. Keep it short, keep it consistent (i.e. if you use hyphens, underscores, or CamelCase for one, use the same format for the others), and make sure the name is based on the function or meaning of the element, NOT the style to be applied.
e.g.
<span class="warningMessage">, <span class="warning-message">, <span class="warning-message"> are all perfectly acceptable.
<span class="red-text"> would not be ... what happens when you change the colour to blue?
I name my ids and classes for their purpose. I try not to use descriptions that use color or direction.
For example, if I have a sidebar that is on the left, but it's for the main menu, I may name it #main or #mainMenu. The right sidebar in the same site would be #altSidebar or #subMenu.
I have many more classes than id's so naming them is a little harder.
Personally, I like to name IDs and Classes with lower-case names ranging from 1 to 3. Example would be ...
.user
.user-profile
.user-profile-picture
And if I want to style another user using classes ...
.user-2
.user-2-profile
.user-2-profile-picture
Like the others have said, you should not use attributes as names, rather, you should use elements like ...
user, picture, header, message, text, input, output.
And so on.
Do not use attributes, like ...
red, big, left, dark, light ...
These are bad because they could change from red to blue for example. But user will always be user.