Should we avoid using ID as CSS selector - html

I am talking about a whole new project, instead of legacy code, since I know sometime it takes so long duration and effort to refactor legacy code.
You may already know that the specificity of using ID as CSS selector is higher than using class name as CSS selector, so it is much more harder to override ID selector than class name selector.
<div class="class-a" id="id-a">Lorem Ipsum</div>
<style>
#id-a{
color: blue;
}
.class-a{
color: red;
}
</style>
E.g. For the code above, the text Lorem Ipsum will always in color blue instead of red even though the class name selector is being written after the id selector.
So why should someone use id as selector instead of using class name? Shouldn't we just use class name and maybe some time with tag name and totally avoid using id as CSS selector and leave id for javascript selector(Since it is much more efficient than using class name and tag name)?
If you would like to have a selector which is kind of unique to yourself and someone who are going to take up your code, you could actually do something like below.
<nav class="navigation-bar" id="navigation-bar">...</nav>
Use a same class name as the id of the element!
This is what I think, but I often see other developer using ID as CSS selector, why do so many people do that? Did I actually missed something? If yes, please let me know.
Thanks in advance.

ID is supposed to be unique but CLASS can be reused many times. Its better to use CLASS if you use frequently.

Related

Is it OK to use id attribute in component's html?

Consider a component c with html
<form id="someID"[formGroup]="codeEditorForm" novalidate>
</form>
with css
#SomeID{
color:grey;
}
If C gets included in a parent component P two times then wouldn't the id get duplicated as well which should not happen in html
Question 1 - should I not use id in Angular?
Question 2 - how shall I then write css rules without using id?
You can use IDs but generally you don't need to do it.
Angular scopes the styles automatically, so a class defined in one component won't affect a class with the same name in another component.
<form id="someID" class="my-form" [formGroup]="codeEditorForm" novalidate>
</form>
.my-form {
color: green;
}
Also note that you should make sure that there is always a space after you define a property. In your posted example there was no space after someId" Maybe it doesn't matter in this case but I guess it's better to start looking out for small things like this right away.
As far as I know there are there are two differences between id and class.
First is that id is used for single specific element, while class can target multiple elements, this means that you normally would use id selector if you are sure that an element will not be repeated, something like navbar.
And the second one is that id selector is more specific than class selector, this means that if there are any conflicts of styles, rules written in id selector override rules written in class selector
Normally you would not use it to override rules as there is other way to do it, so in order to decide which one to use all you need to do is think about this >> is the element you are giving id to really gonna be unique?
Angular support id on html. But as you are loading multiple times the 'C' component on your 'P' component,so the Id will be duplicated. So better you use class instead of id on your html..
<form class="yourClass"[formGroup]="codeEditorForm" novalidate>
</form>
On your 'C' component's css,
.yourClass{
color:grey;
}

What is the difference between id and class in html/css [duplicate]

This question already has answers here:
Difference between ID and Class
(8 answers)
Closed 8 years ago.
I want to know what is the exact difference between id and class in html and css.
I read somewhere that ids are unique and there can be only one element with corresponding id, and classes can be applied to many elements.
But I think this is wrong I have a code in which I have applied a single id to two elements.
<link type="text/css" href="main.css" rel="stylesheet">
</head>
<body id="header">
<p id="header2">Poster</p>
<p id="header2">Hello World</p>
</body>
</html>
and here is my css code
p#header2{
background-color:white;
width:50%;
height:50%;
margin-left:25%;
margin-right:25%;
text-align:center;
font-size:50px;
}
Could anyone please explain me???
Here is the Explanation in detail.
Use a class when you want to consistently style multiple elements throughout the page/site. Use the ID when you have a single element on the page that will take the style. class is a type of item and id is the unique name of an item.
EDIT:
CSS doesn't care
Regarding CSS, there is nothing you can do with an ID that you can't do with a Class and vice versa. I remember when I was first learning CSS and I was having a problem, sometimes I would try and troubleshoot by switching around these values. Nope. CSS doesn't care.
Javascript cares
JavaScript people are already probably more in tune with the differences between classes and ID's. JavaScript depends on there being only one page element with any particular, or else the commonly used getElementById function wouldn't be dependable. For those familiar with jQuery, you know how easy it is to add and remove classes to page elements. It is a native and built in function of jQuery. Notice how no such function exists for ID's. It is not the responsibility of JavaScript to manipulate these values, it would cause more problems than it would be worth.
EDIT2:
The Documentation clearly shows that HTML required the ID attribute to be unique in a page:
This attribute assigns a name to an element. This name must be unique in a document. If you have several elements with the same ID, your HTML is not valid.
So in JavaScript, getElementById() should only ever return one element. You can't make it return multiple elements.
Well, you can have more than one element with the same ID, but you shouldn't - because the consequences of doing so is unpredictable, due to differences between browsers.
ID: Id name must have 1.
<link type="text/css" href="main.css" rel="stylesheet">
</head>
<body id="header"> // ID
<p id="header2">Poster</p>
<p id="header2">Hello World</p>
</body>
</html>
Class: have multi tag using the same class name. And you can apply style for all class have name is "name".
<p class = "name">abcdef</p>
<image class = "name">......</image>
It's right:
The id of an element should be unique in the entire dom.
The class can be applied to multiple elements.
In css if you use this syntax
.yourClass {
color: white;
}
every element with class="yourClass" have the style color: white.
The id HAVE to be unique for different reason. The thing first jump into my mind its the use of jquery where you identify dom elements with the ID
The id attribute is meant to be unique and should contain a single identifier. The class attribute may contain a space-separated list of class identifiers allowing for cumulative application of css rules.
This is notwithstanding to css engines that do not complain on double ids.
Simple - id is the one that can be used only once and it will be unique. Scripts mostly use id's but it doesn't mean that id will only be used with js and not css. You can used a id as selector to in css.
While classes when two or more divs have the same styling so use class instead of increasing lines of codes.

Which to use <div class="name"> or <div id="name">? [duplicate]

This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 9 years ago.
I am learning HTML. Can someone please tell me what is the difference between class and id and when to use one over the other? They seem to do the same thing
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycolor1 {color: red;}
.mycolor2 {color: red;}
</style>
</head>
<body>
<div id="mycolor1"> hello world </div>
<div class="mycolor2"> hello world </div>
</body>
</html>
They do not do the same thing.id is used to target a specific element, classname can be used to target multiple elements.
Example:
<div id="mycolor1" class="mycolor2"> hello world </div>
<div class="mycolor2"> hello world2 </div>
<div class="mycolor2"> hello world3 </div>
Now, you can refer all the divs with classname mycolor2 at once using
.mycolor2{ color: red } //for example - in css
This would set all nodes with class mycolor2 to red.
However, if you want to set specifically mycolor1 to blue , you can target it specifically like this:
#mycolor1{ color: blue; }
Read the spec for the attributes and for CSS.
id must be unique. class does not have to be
id has higher (highest!) specificity in CSS
Elements can have multiple non-ordinal classes (separated by spaces), but only one id
It is faster to select an element by it's ID when querying the DOM
id can be used as an anchor target (using the fragment of the request) for any element. name only works with anchors (<a>)
Classes should be used when you have multiple similar elements.
Ex: Many div's displaying song lyrics, you could assign them a class of lyrics since they are all similar.
ID's must be unique! They are used to target specific elements
Ex: An input for a users email could have the ID txtEmail -- No other element should have this ID.
The object itself will not change. The main difference between these 2 keyword is the use:
The ID is usually single in the page
The class can have one or many occurences
In the CSS or Javascript files:
The ID will be accessed by the character #
The class will be accessed by the character .
To put it simnply: id is unique to just one element in the whole HTML document, but class can be added to numerous elements.
Also, ID properties have priority over class properties.
ids and classes are especially useful if you plan on using javascript or any of its frameworks.
class is used when u want to set properties for a group of elements, but id can be set for only one element.
ID's must be unique (only be given to one element in the DOM at a time), whereas classes don't have to be. You've already discovered the CSS . class and # ID prefixes, so that's pretty much it.
ID provides a unique indentifier for the element, in case you want to manipulate it in JavaScript. The class attribute can be used to treat a group of HTML elements the same, particularly in regards to fonts, colors and other style properties...
ID is suitable for the elements which appears only once
Like
Logo sidebar container
And Class is suitable for the elements which has same UI but they can be appear more than once.
Like
.feed in the #feeds Container
the Id selector is used when referring to a single unique element.
The Class selector referrers a group of elements.
For example, if you have a multiple buttons that look the same, you should use class="mybutton" to have consistent styling.
In terms of performance:
CSS selectors are matched from right to left.
Therefore, .myClass should be "faster" than #myID because it misses out testing.
The performance speed is negligible for normally sized pages and you will probably never notice a difference so it's mostly just about convention.
Here is more info on why css is browsers match css selectors from right to left

CSS selector with period in ID

The HTML spec allows for periods (.) in an id:
<img id="some.id" />
However, using a CSS ID selector rule will not match correctly:
#some.id { color: #f00; }
The CSS spec for ID Selectors does not mention this case. So I assume it is using the combination of a tag name and class selector? For example, a CSS rule of a.className would apply to all anchor tags (<a>) with a class name of className, like <a class="className"></a>.
Is it possible to have an external CSS file rule that references an HTML element by its id that has a period in it?
I expect not since the CSS spec specifies that a CSS "identifier" does not include the period as a valid character. So is this a fundamental mismatch between HTML and CSS specs? Is my only alternative to use a different type of CSS selection? Can anyone smarter than I confirm or deny this?
(I would remove the period from the HTML id attribute to simplify things, but it is a system-generated id, so I don't have the ability to change it in this case.)
After digging through the specs some more, I found the CSS spec does allow for backslash (\) escaping like most languages.
So in my example, the following rule would match:
#some\.id {
color: #f00;
}
You could also use the attribute selector like this:
[id='some.id'] {
color: #f00;
}
Since you are using id, you can also use document.getElementById() which checks the id value as a normal string and not a CSS selector.
e.g. the following works too:
const myElem = document.getElementById("some.id");
The only drawback is, you can't limit the scope of search, like you could with querySelector e.g. someElement.querySelector().
but since Ids should always be unique, a document wide search with id is valid.

How to select inner divs with the IDs?

I would like to select a div within a div by specifying the ID.
HTML with specified ID
<div id="divOuter">
<div id="divInner">
</div>
</div>
And if I want to select divInner by using ID selectors in more to the point style what should I use?
I tried
div#divOuter> div#divInner
but cannot make it work.
As IDs have to be unique,
#divInner
is sufficient.
If you have more elements with the same ID you have to change that (you might want to use classes instead).
Update:
Ok, I got your point. But your selector is correct: http://jsfiddle.net/fkling/AsPam/
Either you have another rule that overrides this one, or your structure is different.
Update 2:
Oh, as others have noted , the child selector is not supported by IE6. You have to omit it then:
div#divOuter div#divInner
As IDs are unique all you really need is
#divInner
{
/*styles*/
}
This will select the ID attribute of the HTML element and apply the styles.
If you need to repeat the styles to more than one element, use a class
.divInner
{
/*styles*/
}
#divOuter div{...}
or
#divInner{...}
For starters (and I know this might be a typo), have you checked the spelling?
When it comes to the selection, you seem to want to use the id tag, in other words, all you need is to do as everyone above says: #idInner{...}