html....
<div class="one two">test</div>
<div class="two one">test</div>
css....
.one.two{
color: red;
}
.two.one{
color: blue;
}
I was supposing to have the first div color to be red and second div color to be blue, but it's taking lastly specified style rules for the both of the div that is color blue.
So, I wonder why the ordering of the classes are not maintained?
If this was what I was expecting, would it be an advantage or a disadvantage?
Think about it semantically: A class is just that - some encompassing category to which an element belongs.
If we take the example of a table, some plausible classes might be: "rounded-border" and/or "fixed-width" and/or "blue-background". Suppose a particular table has all of these three classes. If ordering were important, you would require six CSS selectors to target all tables that have these classes instead of just the one.
If the ordering of classes is important in distinguishing between two elements, then create two different classes for them. E.g. one-two and two-one.
Both selectors, .one.two and .two.one, match both div elements here, and the selectors have the same specificity. Thus, by the CSS cascade rules, the latter declaration wins.
The mutual order of the class selectors is irrelevant by definition: the meaning of a class selectors is defined so that the order does not matter.
Moreover, even if it mattered, the HTML attributes class="one two" and class="two one" would still be equivalent, due to the way the the class attribute has been defined in HTML specifications.
What you should do depends on what you wish to accomplish. The question does not specify that. If you need to make the styling of elements depend on the order in which their classes are written in a selector, there is a flaw in the design of markup and styling.
I was reading above discussion and I agree with what BoltClock♦ says and others as well.
but I was refering this Does the order of classes listed on an item affect the CSS?, the use of attribute selectors in CSS where ScottS answered with some
demo 1 demo 2 demo 3
and now I am muddled with whole thing! BoltClock♦ can you please put some more light on the same?
Related
So, I was looking at a tut on youtube the other day, and this guy kept defining css rules with classes really weirdly, and I wondered if one of u guys could explain the necessity of it: here is the code:
ul.class li{
color:#fff
}
Why can't he just do:
.class{
color:#fff
}
Thank you for reading my question, I hope you understand what I am asking for.
Video: https://youtu.be/2wCpkOk2uCg
P.S - Sorry for the giganticly large title 😏
When you put the element before the class, CSS only applies the styles to the members of that class that are of that specific element.
For example, if you had .class applied to 3 headers and 3 paragraphs, writing p.class would only affect the paragraphs.
With ul.class you're saying "Apply this styles to all the ul's with this class. If you only use .class you're saying "Apply this styles to ANYTHING that has this class". It's very different. :)
I can think of at least two reasons to include the element name as well as the class:
Specificity, i.e., which CSS rule takes effect on a target element when multiple rules apply to to it. There is a specificity algorithm that determines which rule is applied when multiple rules are in competition. This awesome Specificity Calculator is a great tool to help you understand the algorithm. So, in short, including the element name and the class gives it additional weight.
Documentation in your CSS. I tend to include the element as well as the class, e.g. h1.customer-name, to self-document what type of element the rule is being applied to. When I see .customer-name without the element name, I am not totally confident in what type of HTML element it is. Doing this means I don't have to keep the HTML structure in my head or consult the HTML repeatedly while I work on CSS. But this is pretty dependent on one's approach to CSS as well as the tools used, so I'm not sure I would consider it a good idea across the board.
And one more, but not least important thing. If you adding the tag name before the class name (such as span.class{}), so you got more specific rule and it's have bigger priority (no matter in which order that rules writter in css file). For example, if you write two rules:
.class { color: red }
and
span.class { color: blue }
you will get a blue text as a result.
This question already has answers here:
Understanding CSS selector priority / specificity
(4 answers)
Closed 5 years ago.
If I declare in my css file(or inside <style> </style> tags) firstly the id of element and then the classname of the same element, then the id styling will be applied, regardless the fact that classname is the latest one in order.
I want to know why this is happening and if it has some naming, please do tell.
Just to make it more clear, take a look at this example, please:
div {
height:100px;
width:150px;
border:1px solid #000;
margin:0 auto;
}
#theID {
background:#090;
}
.theCLASS {
background:#00F;
}
<div id="theID" class="theCLASS"></div>
This is to do with the complicated world of "Specificity"...
ID's are more specific than classes and take precedence over them. This is because ID's have to be UNIQUE on every page...so they are by nature very specific. Classes can appear multiple times.
Learning how this works is fundamental to coding CSS. Some people say you should try to avoid using ID's altogether as they are so specific they tend to cut down reuse.
A rule of thumb might be to use ID's to identify large sections of your page, or important items and classes to attach styles to the other things.
These days with html5 we have <section>, <header> and <footer> whereas we used to use div's for those (with ID's normally) so these days the ID is used less than ever since we can target those things directly.
However consider ID-ing sections: <section id="mainContent"> for example is a fairly standard thing to do.
There are no RULES about how to specifically (excuse the pun) use ID's and classes. Just conventions that have built up over time.
see: https://developer.mozilla.org/en/docs/Web/CSS/Specificity ... here is a section:
The concept
Specificity is the means by which browsers decide which CSS property
values are the most relevant to an element and, therefore, will be
applied. Specificity is based on the matching rules which are composed
of different sorts of CSS selectors.
How is it calculated?
Specificity is a weight that is applied to a given CSS declaration,
determined by the number of each selector type in the matching
selector. When specificity is equal to any of the multiple
declarations, the last declaration found in the CSS is applied to the
element. Specificity only applies when the same element is targeted by
multiple declarations. As per CSS rules, directly targeted element
will always take precedence over rules which an element inherits from
its ancestor.
It carries more specificity
CSS applies vastly different specificity weights to classes and IDs.
In fact, an ID has infinitely more specificity value! That is, no
amount of classes alone can outweigh an ID.
CSS Tricks - Specifics on CSS Specificity
Further Reading:
CSS Tricks - The Difference Between ID and Class
MDN - Specificity
Selector Types
The following list of selector types increases by specificity:
Type selectors (e.g., h1) and pseudo-elements (e.g., :before).
Class selectors (e.g., .example), attributes selectors (e.g.,
[type="radio"]) and pseudo-classes (e.g., :hover).
ID selectors (e.g., #example).
This question already has answers here:
What's the difference between an id and a class?
(17 answers)
Closed 5 years ago.
#main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div id="main">
Welcome
</div>
Here I gave an id to the div element and it's applying the relevant CSS for it.
OR
.main {
background: #000;
border: 1px solid #AAAAAA;
padding: 10px;
color: #fff;
width: 100px;
}
<div class="main">
Welcome
</div>
Now here I gave a class to the div and it's also doing the same job for me.
Then what is the exact difference between Id and class and when should I use id and when should I use class.? I am a newbie in CSS and Web-design and a little bit confused while dealing with this.
Use a class when you want to consistently style multiple elements throughout the page/site. Classes are useful when you have, or possibly will have in the future, more than one element that shares the same style. An example may be a div of "comments" or a certain list style to use for related links.
Additionally, a given element can have more than one class associated with it, while an element can only have one id. For example, you can give a div two classes whose styles will both take effect.
Furthermore, note that classes are often used to define behavioral styles in addition to visual ones. For example, the jQuery form validator plugin heavily uses classes to define the validation behavior of elements (e.g. required or not, or defining the type of input format)
Examples of class names are: tag, comment, toolbar-button, warning-message, or email.
Use the ID when you have a single element on the page that will take the style. Remember that IDs must be unique. In your case this may be the correct option, as there presumably will only be one "main" div on the page.
Examples of ids are: main-content, header, footer, or left-sidebar.
A good way to remember this is a class is a type of item and the id is the unique name of an item on the page.
ids 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.
Javascript cares
JavaScript people are already probably more in tune with the differences between classes and ids. JavaScript depends on there being only one page element with any particular id, or else the commonly used getElementById function couldn't be depended on.
For more info on this click here.
Example
<div id="header_id" class="header_class">Text</div>
#header_id {font-color:#fff}
.header_class {font-color:#000}
(Note that CSS uses the prefix # for IDs and . for Classes.)
However color was an HTML 4.01 <font> tag attribute deprecated in HTML 5.
In CSS there is no "font-color", the style is color so the above should read:
Example
<div id="header_id" class="header_class">Text</div>
#header_id {color:#fff}
.header_class {color:#000}
The text would be white.
IDs must be unique--you can't have more than one element with the same ID in an html document. Classes can be used for multiple elements. In this case, you would want to use an ID for "main" because it's (presumably) unique--it's the "main" div that serves as a container for your other content and there will only be one.
If you have a bunch of menu buttons or some other element for which you want the styling repeated, you would assign them all to the same class and then style that class.
As pretty much everyone else has said use ID for one-off elements and class for multiple use elements.
Here is a quick, over simplified example, take HTML and HEAD tags as read
<body>
<div id="leftCol">
You will only have one left column
</div>
<div id="mainContent">
Only one main content container, but.....
<p class="prettyPara">You might want more than one pretty paragraph</p>
<p>This one is boring and unstyled</p>
<p class="prettyPara">See I told you, you might need another!</p>
</div>
<div id="footer">
Not very HTML5 but you'll likely only have one of these too.
</div>
</body>
Also, as mentioned in other answers ID are well exposed to javascript, classes less so. However modern javascript frameworks like jQuery leverage class for javascript too
ID's have the functionality to work as links to particular sections within a webpage.
a keyword after # tag will take you to a particular section of the webpage.
e.g "http://exampleurl.com#chapter5" in the address bar will take you there when you have a "section5" id wrapped around the chapter 5 section of the page.
The class attribute can be used with multiple HTML elements/tags and all will take the effect. Where as the id is meant for a single element/tag and is considered unique.
Moreoever the id has a higher specificity value than the class.
id:
It will identify the unique element of your entire page. No other element should be declared with the same id.
The id selector is used to specify a style for a single, unique element.
The id selector uses the id attribute of the HTML element, and is defined with a "#".
class:
The class selector is used to specify a style for a group of elements. Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
If there is something to add to the previous good answers, it is to explain why ids must be unique per page. This is important to understand for a beginner because applying the same id to multiple elements within the same page will not trigger any error and rather has the same effects as a class.
So from an HTML/CSS perspective, the uniqueness of id per page does not make a sens. But from the JavaScript perspective, it is important to have one id per element per page because getElementById() identifies, as its name suggests, elements by their ids.
So even if you are a pure HTML/CSS developer, you must respect the uniqueness aspect of ids per page for two good reasons:
Clarity: whenever you see an id you are sure it does not exist elsewhere within the same page
Scalability: Even if you are developing only in HTML/CSS, you need to take in consideration the day where you or an other developer will move on to maintain and add functionality to your website in JavaScript.
You can assign a class to many elements. You can also assign more than one class to an element, eg.
<button class="btn span4" ..>
in Bootstrap. You can assign the id only to one.
So if you want to make many elements look the same, eg. list items, you choose class. If you want to trigger certain actions on an element using JavaScript you will probably use id.
A class can be used several times, while an ID can only be used once, so you should use classes for items that you know you're going to use a lot. An example would be if you wanted to give all the paragraphs on your webpage the same styling, you would use classes.
Standards specify that any given ID name can only be referenced once within a page or document. Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.
This is very simple to understand :-
id is used when we have to apply CSS property to one attribute only.
class is used when we have to use CSS property in many locations within the same page or different.
General :- for unique structure like staring div and buttons layout we use id .
for same CSS throughout the page or project we use class
id is light and class is little heavy
A simple way to look at it is that an id is unique to only one element.
A class is not unique and applied to multiple elements.
For example:
<p class = "content">This is some random <strong id="veryImportant"> stuff!</strong></p>
Content is a class since it'll probably apply to some other tags aswell where as "veryImportant" is only being used once and never again.
Unlike the id selector, the class selector is most often used on several elements.
This allows you to set a particular style for many HTML elements with the same class.
The class selector uses the HTML class attribute, and is defined with a "."
A simple way to look at it is that an id is unique to only one element. class is better to use as it will help you to execute what ever you want.
id selector can be used to more elements. here is the example:
css:
#t_color{
color: red;
}
#f_style{
font-family: arial;
font-size: 20px;
}
html:
<p id="t_color"> test only </p>
<div id="t_color">the box text</div>
I tested on internet explorer (ver. 11.0) and Chrome (ver.47.0). it works on both of them.
The "unique" only means one element can not have more than one id attributes like class selector. Neither
<p id="t_color f_style">...</p>
nor
<p id="t_color" id="f_style">...</p>
I can very well understand from this Selectutorial what element/tag based descendant selectors are, how and why they work and for what purpose.
But then I came across certain websites which define a class name for an anchor <a> which is made of several names separated by spaces, e.g.
<a class="samename nav_item samename" href="/messages/?refid=7"> Text </a>
I then found out that these are also called "descendant selectors" -- or are they called descendant combinators?
This is where I stopped understanding:
Is the 2nd type of "descendant
selectors" the same as the 1st type?
Does the 2nd type of "descendant
selectors" have a different name,
that can help me differentiate it
from the 1st type when referring to
it?
What is the purpose of this 2nd type
of "descendant selectors"?
Why repeat samename in such
descendant selector?
Any tips or pointers to places where I can learn more about this 2nd type would be much appreciated.
EDIT: The replies below helped put order into things, especially in regard to proper terminology. I will try to summarize my understanding so far -- first by attempting to answer the questions above in a respective manner, then listing some insights, with the hope that it can help future css-laymen like me:
The 2nd type is not "descendant
selectors" at all, so it cannot
possibly be the same as the 1st
type.
The name for the 2nd type, for now,
is multiple class names assigned to the same tag.
One use of attributing multiple classes per element is that one can then chain class selectors, such that only elements with all the classes listed are matched, not those that have one or fewer of the classes.
This is most likely a programming mistake/error/bug (although I found it on a very prominent website).
Insights (please correct if you spot a mistake):
Despite what's written in
w3schools, a class (name) is
not a selector! A selector can only be an HTML element.
However, a CSS rule may refer
to an HTML element (or a group of
HTML elements) by class name, using
the .classname notation. This
notation is referred to by some as
"the class selector" and this
is where my confusion stemmed from. It merely means it can be used to select any HTML element that has a class attribute.
A CSS rule may also refer to an HTML
element (or a group of HTML
elements) by element id, using the
#elementid notation. This is an
entirely different subject but since
this notation is referred to by some
as "the id selector" it's quite
possible this could be a source for
confusion as well, so it's briefly
mentioned here.
In HTML, "class" is an attribute. In
CSS, it is a "selector aggregator",
used to select any HTML element that
has that class attribute.
The best CSS tutorial, by far, is
Selectutorial.
There is only one CSS descendant selector, and that is the space character:
E F /* Selects any F that descends from (or is contained by) an E */
Space-separated class names are just multiple classes that are separated by spaces, in a single HTML class attribute. The class attribute is not a selector, in fact not even part of CSS for that matter.
On a somewhat related note, however, one use of listing multiple classes per element is that you can then chain class selectors, such that only elements with all the classes listed are matched, not those that have one or fewer of the classes. For example:
.samename.nav_item /* Selects only elements that have both classes */
As to why samename is repeated in your given HTML, I have no idea. It's the same as having just one samename class.
In your example, the a tag actually has several different classes (of which one is listed twice, for some reason).
In CSS code, we'd use a space to separate decendant selectors, but in HTML it just lets us put several classes in the same set of parentheses.
Ive been wondering... in CSS are there any differences between creating a style class and applying it an element, or creating a style with the #elementId notation (apart from being able to assign a class to different elements)?
For example...
#div1
{
background-color: Yellow;
}
<div id="div1">
Hello world!
</div>
Or
.div1
{
background-color: Yellow;
}
<div class="div1">
Hello world!
</div>
Thanks! :)
An ID must be unique in a document. Classes can be used in any number and combination. So you can use one class on multiple elements and multiple classes on one element.
One other difference; id-selectors are more specific than class-selectors, so I believe they will "trump" any other selector that exists. You can use "important" to do the same thing, but and id selector may be easier.
But id-selectors should be used sparingly...
Many classes can include a given "class" while only one element may be identified by a given ID. If you need to locate an unique Element use ID, otherwise if you wish to mark many elements that are basically the same but in different spots in your html use 'class'.
You sort of answered your own question, they are just mechanisms to 'identify' elements.
using #elementID applies only to the element uniquely identified by that id. a class can be used by multiple elements
there is however an order of precedence. selectors using the id have greater weight than selectors using class and when there is a collision the #id selector will take precedence
edit: see http://kiribao.blogspot.com/2008/03/css-selectors-precedence-and-ways-to.html for more detail on selector precedence
edit: also see the w3c specs at http://www.w3.org/TR/CSS21/cascade.html#specificity
Performance or functionality-wise, there is no difference [citation needed].
The only real difference is semantic, if you are working on a single node with a unique ID, or if you need a reusable class marking several nodes.
There are some differences:
Uniqueness
IDs must be unique, classes can be repeated. This is logical if you look at their expected usage.
Usage
IDs should be used to denote large sections of a website (e.g. #header), or unique elements that are accessed via Javascript (e.g. #killSession)
Classes should be used for reusable parts.
Specifity
IDs get assigned a specifity value of 100, while classes are only worth 1.
So this rule:
#id .class
Is worth 101 points.
This rule:
#id #id2
Is worth 200 points and will always trump the #id .class rule (regardless of the source order).
Performance
Performance wise, getting elements by ID is always faster than class, especially when talking Javascript. I'd love to see someone add some cold hard numbers to this.
Discussion
An interesting discussion about the performance of selectors can be found at Shaun Inman's blog.
The usage of classes is debated in Jeff Croft Applying OOP concepts to CSS
Classes are to group together elements which share similar functionality (for scripting) and/or layout (for styling). IDs should always be unique identifiers for elements.
A good example for something which should have an ID is the content area of your document, which is common to use the #content ID for. Classes are good for anything else which may occur twice in your document, such as headers which should have special markup or behavior, or links which should open a lightbox instead of the normal "go to URL" behavior.
HTH.