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.
Related
While I don't need convincing that id selectors should be used sparingly and that class selectors should be used primarily for applying CSS , I'm having trouble explaining it to members of my group project. When we met as a group to go over everyone's HTML and CSS files, I noticed they used id selectors for almost everything(including elements that weren't unique). While I explained that id selectors should be used to style very unique elements only in CSS and class selectors should be used for applying CSS to everything else due to their re-usability, now I'm trying to remember other reasons. So my question is what other reasons are there for using class selectors over id selectors for non-unique elements?
As you mentioned, the uniqueness of ids is reason enough to not use them as selectors, but there are more:
An element can have several classes, but only one id. You might want to same element to be both a .news-article and .breaking-news. If you use JavaScript you can have one class for styling (.unstyled-list) and another for your script (.side-menu). That way you can change your list to .roman-numerals without breaking your script.
What makes ids even worse for applying styles is the combination of their uniqueness and their higher specificity. If you use ids for styling you will surely get stuck in a specificity race (especially if you need to maintain the CSS over time, which is probably the case).
Currently the most common way to identify the current link is adding a class to the anchor or its parent:
<li class="active">Home</li>
This technique has a couple of drawbacks:
Adding the class is often delegated to server languages and it means an extra work just for presentation.
Even though there is a convention around the active class name, it's a stupid selector and doesn't seem to be semantically correct.
I tried the following with no success:
I looked for something like the :target pseudo-class, so the selector could be: a:current, unfortunately it doesn't exist yet.
I thought the rel attribute was a good candidate, but I couldn't find any that fit.
Adding and attibute to the nav that sets the current link, but we need to add ids to every link, and CSS will become verbose
<style>
[data-active^="home"] a[id^="home"]{ color:red; }
</style>
<nav data-active="home-link"><ul>
<li><a id="home-link">Home</a>
...
Is there a different way to select current links that is semantically correct?
The purpose of selecting with CSS the current or active link is to give the user a clue about the section or document is currently viewing. As #BoltClock pointed out the active class is semantically meaningless and the question is if there is a semantically meaningful way to select the link that belongs to the section or document the user is visting?
I looked for something like the :target pseudo-class, so the selector could be: a:current, unfortunately it doesn't exist yet.
Indeed, no such selector exists yet, so what you have is already your best bet. The following pseudo-classes sound like they might be what you're looking for, but they mean different things:
:active matches an element that is being designated by the cursor; usually this means an element that is being clicked.
:target matches an element whose ID matches the URL hash fragment, which means it only works for hash fragments and not the URL path itself.
:current appears in Selectors 4, but it means something quite different entirely: it matches the chronologically current element. Since HTML itself doesn't have a concept of a timeline, :current will match nothing (although I can imagine captioning or AT tools making full use of it in an HTML document).
That said, there is in fact a pseudo-class being proposed in Selectors 4 that targets the current document, only it's called :local-link:
a:local-link { color: red; }
Of course, no implementations actually exist yet, so you're stuck with using a class name for the foreseeable future.
As helion3 has pointed out, the reason class names are used is because they're the easiest solution that exists today, and is tried, tested and true tradition dating back decades. Keep in mind that even HTML does not have "current-document" semantics beyond URL fragments, so you're really not going to be able to go any further than a class name or a custom data attribute with a hardcoded value.
I don't disagree with that article you've linked to either, but given there isn't in fact a "semantically correct" approach to this since no pseudo-class exists with the proper semantics, again you're basically stuck with this. If it makes you feel better, note that class names aren't really semantically incorrect in this case, rather they are semantically meaningless, i.e. they have no influence whatsoever on the meaning of the context they are in, or the document as a whole.
current is a concept that CSS doesn't have because CSS isn't involved with route handling. We use the active/current/at class names because it's the easiest way.
Javascript can easily set/remove classes based on routing, as can server-side languages.
Also, navigation structures are different and in your example, it's not the anchor that's active, but the li. That should be left to developers to establish based on the needs of the styles.
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.
I'm wondering if there is any difference between div.class and .class as CSS selectors if there is only one tag (the DIV) with that attribute. Same thing for IDs: div#ID and #ID.
Any idea what, if anything, is the difference? For me, I use the class or ID in these situations; but only because it's quicker to type.
They are more specific, so long ones will override the shorter version if they conflict. div.foo will have a specificity of 11 while .foo has a specificity of 10.
Since they are more specific, you know exactly which nodename the class applies to instead of being a universal rule for all node names, this can help if you have a huge application with tons of elements that all have the same class names, it can lessen the time for you to find the element in the source/text editor.
There is only a VERY SLIGHT difference in specificity.
p#id is (0,1,0,1)
and
#id is (0,1,0,0)
in otherwords, the tag itself doesn't hold very much specificity at all compared to an ID, and relying on that kind of tiny specifity to overrule things is almost never needed in my experience.
More importantly, NOT tag-qualifiying selectors is more efficient for the browser to render.
Sticking to just a class or id, as you do, means that your CSS will still apply if the HTML tag is changed to a different tag.
Most of the time, this is probably exactly what you want — classes are there to allow you to add a custom layer of meaning on top of HTML.
In general, your selectors should be the minimum required to express your meaning.
Usually those longer selectors come in handy once the majority of the CSS has already been done. Sometimes you want to tweak a little thing here and there - say - differenciate between p.error and div.error for example. So instead of adding another class - and thus having to touch the HTML - you can simply add an element name to your selector instead, for more fine grained control.
No, there is no difference if you only have DIV tags of the specific class or ID.
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.