css selecting a lot of ids classes - css

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;}

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.

Using same ID for multiple HTML tags? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Several elements with the same ID responding to one CSS ID selector
Below is the example code that I was testing and I got confused. Every one says that we can use or we should use only one time per id, but I have testes using using it multiple times but its giving me the correct output.
What should I do?
It's kinda working same like class for me in this example
code:
<html>
<head>
<style>
#exampleID1 { background-color: blue; }
#exampleID2 { text-transform: uppercase; }
</style>
</head>
<body>
<p id="exampleID1">This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.</p>
<p id="exampleID2">This paragraph has an ID name of "exampleID2" and has had its text transformed to uppercase letters.</p>
<address id="exampleID1">
Written by W3Schools.com<br />
Email us<br />
Address: Box 564, Disneyland<br />
Phone: +12 34 56 78
</address>
<blockquote id="exampleID1">
Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.
</blockquote>
</body>
</html>
Please see the above code and answer me that why we should not use id selector two times in a page while its working fine.
An id must be unique in a page. Use a class if you want to describe a group of elements.
why we should not use id selector two times in a page while its working fine.
You are making an error and depending on every browser that will ever view the page to compensate for it. You can't be sure they all will.
I think the easier way to understand is doing an analogy with a product. Imagine that an ID works like a Serial Number, in other words, it must be unique, this way you can identify a product that have milions of equal copies.
Then, imagine the class as the Product Code, can be the bar code for example. In a supermarket all equal products have the same bar code to be read by optical reader.
So, an ID is an unique identifiquer and a class groups a group of elements.
But if i am using the same ID in my HTML/CSS i am get a perfect result, why should i be worried about unique IDs?
Reason number 1:
In the future, if you need to use Javascript and if you need to manipulate an specific element and it has a duplicated ID, your code will not generate the expected result.
Reason number 2
Your code will not be valited by W3C, what means that you can have headaches with your website's compability accross browsers. It can works fine in one browser and in other not.
Using a real example, imagine that you want to update dinamically, using Javascript, the text of this element:
<blockquote id="exampleID1">
Here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation here is a long quotation.
</blockquote>
With Javascript/JQuery you will use a code like this:
$("#exampleID1").html("Changing element content");
And then the text of the element <blockquote id="exampleID1"> will be updated, but the below element will be updated too, because it has the same ID.
<p id="exampleID1">This paragraph has an ID name of "exampleID1" and has a blue CSS defined background.</p>
So, if you want to update just one element, they must have unique IDs.
I hope you can use this explanation to understand better the difference between ID and class.
It's working, but that's not the way IDs are meant to be used (according to the HTML specifications).
An ID must refer only to one object.
Describing multiple objects must be done with class, not id.
You should use unique Ids to ensure the HTML is valid.
The reasoning behind this is simply that Ids are used to identify unique elements.
The page will still render, despite being invalid, but the biggest practical problem is that JavaScript and other libraries are optimised to work on the assumption that Ids are unique so, if you are trying to fetch all elements with an Id and hide them e.g. using jQuery
$('#exampleID1').hide();
Only the first element will be hidden, since to select by Id should only return a single item and once a single element is found the query is short circuited to return the single element. Without knowing this you can get some seemingly odd behaviour and hard to diagnose defects.
why we should not use id selector two times in a page while its
working fine
Because you don't know if it's working fine in every browser.
The specifications says that an id has to be unique in the page, so when browsers find your duplicate id:s they will try to handle it as best they can. Most browsers seem to handle it by using the identity only for the first element, but leaving the id attribute on the elements so that your CSS still works, but there is no guarantee that all browsers handle it that way.
Different browser vendors use different tactics for handling incorrect markup, and each vendor finds a "new, better" way, so incorrect markup is typically handled in as many different ways as possible.

Why .classname is worse than element.classname

Can someone help me explain why:
#id .classname
is worse than:
#id element.classname
from a rendering/performance perspective?
Because the DOM has special functions (getElementByTagName) dedicated to find all elements in a tree by their tag name. These functions use lookup tables and are well optimized. No such method exist for classnames, however, and finding a classname requires to iterate through all the tree(s) and check existing classnames. This algorithm can be made quicker by reducing the size of the trees to iterate, and using an element. prefix does just this: it reduces the size of the trees to look for the classname.
simply because .classname has to check all elements for the specifyed classname, while type.classname only hast to check elements matching the specified type.
I think because in the first example, the browser rendering engine should search for every element with class classname inside the #id element.
The second example would be faster because the engine looks just for every element element with that class.
Sorry for the word game, however this should be non influential from a performance perspective.
It's not.
For the first selector, the browser checks if an element has the class, then it checks if any descendant has the id.
For the second selector, the browser checks if an element has the class, then if checks if the element matches the tag name, then it checks if any descendant has the id.
If the selectors have the same effect, the first selector is better, as the browser has to do fewer checks to match the rule.
More information about efficient selectors: http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors
Don't overoptimize your code, make it clear (and this is just about you and your habits, or your team standard) and see about performance later.
When your css selector will be your bottleneck, then you'll have 1 000 engineers working for you.

CSS: are class and id interchangeable?

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.

Resources