ID works same as CLASS - css

I know that ids are for single elements and class is used for multiple elements on the same page. But then why ID styling is applied when there are multiple same ids?
http://jsfiddle.net/WqrAF/
Now, it works then what's the difference?

You cannot select a single id if there are many of it. You will run into problems when you need just one instance of a dom object.

That's because browser try very hard with invalid and malformed markup. They don't always succeed to do what the author intended though.
The solution is to always write valid markup, and check the validation.

This is just the browser coping with invalid HTML. There should never be more than one instance of the id attribute with the same value on one page.

The main difference: for ID, it should not appear in the same HTML more than once; for class, it can be used many times in same HTML.

The behaviour is undefined when you use invalid markup. All major browsers may be able to correct your wrong markup but you cannot rely on that.
Another difference is that ID-Selectors are more specific than Class-Selectors:
inline style
ID
classes
elements
That means an ID-Selector always wins over any class selector - no matter how many class and element tokens the selector contains. (Unless the class selector styles contain !important. But that's about CSS-Importance and not CSS-Specificity then. This is because CSS-Importance takes place before CSS-Specificity is considered.)

Related

XPages CSS and id-attributes

Normally I can get around the fact xpages hijacks the id-attribute on fields etc by using the x$ jQuery selector...
However, I'm building a sylesheet using the #print media query to make a normal form into a pretty version when printed. I have a scenario, where I have a custom control, have given it an ID of GuidanceArea, and under normal circumstances would be able to reference it in my style sheet with #GuidanceArea, just to simply hide it for example for this scenario.
However this isn't working, I assume because of the ID hijacking? It's not too much of a big deal, as I have workaround where for all elements I don't want to print I just append no-print to the elements styleClass and have .no-print set to display:none in my #media print within the style sheet.
However out of curiosity more than anything, I wondered if there's an easy way to get a hold of an elements ID for use in CSS?
The short answer: don't
The longs answer: JSF and XPages manage the id attribute to ensure it is unique on a page. So you don't have actual knowledge what it will be.
The easiest way is to use the class attribute to mark the element of interest, so your selector would be .someclass instead of #someid
But if you absolutely have to: use an XPages output element to send a piece of computed inline css where you use expression language to obtain the actual id. Browsers or libraries might cough on the : in the id, so your result requires lots of testing. VanillaJS should work.

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.

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.

Class Style Sheet with two names or?

<div id="SideBar" class="sidebar mainbar">
I've just seen this in a .aspx file. Is this valid? Can someone point me in the right direction to learn what this does. I'm assuming its valid, but I'm not finding it in the css file. I am finding sidebar defined as a class, but not mainbar.
Thanks in advance,
Randy
This div just has two classes, which means it will get the properties defined under .sidebar as well as those under .mainbar
Sure, you can have an element implement as many css classes as you like. If there is no class defined in the CSS files it is possible that either:
The additional css classes have been removed from the styles sheets and the .aspx pages have not been refactored to match.
The css class is been used to identify the element(s) via javascript or some other scripting language.
As for mainbar not showing up in your CSS file, sometimes developers assign classes to elements and then reference those classes in javascript.
Yes this is perfectly valid. An element can be styled by multiple classes.
See this reference and this one which touches on which one takes precedence for duplicate style attributes.
CSS Tricks has a few other CSS tricks including having two classes.
Copy/Pasting the trick from the above site:
Usually attributes are assigned just one class, but this doesn't mean that that's all you're allowed. In reality, you can assign as many classes as you like!
Using these two classes together (separated by a space, not with a comma) means that the paragraph calls up the rules assigned to both text and side. If any rules overlap between the two classes then the class which is below the other in the CSS document will take precedence.
Beware of IE6 if someday you try to style an element using more than one class, it doesn't work like intended.
Googling "multiple classes ie6"
test case
No problem with id+class (like #anid.class ) or two selectors like .classA and then .classB but no .classA.classB

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