Semantic way to select current or active links in navigation menu - html

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.

Related

Will using IDs more than once cause any troubles, HTML&CSS wise? [duplicate]

Is it safe to give several elements the same ID in one page? For example this often happens, when using some jquery plugins, when you run some slider or gallery twice or more. We know, developers like to give some ID to the html container in order the script works faster.
Let's read w3.org documentation:
What makes attributes of type ID special is that no two such
attributes can have the same value; whatever the document language, an
ID attribute can be used to uniquely identify its element.
But the next example with 2 elements having the same ID works fine in all browsers, though it's not valid:
#red {
color: red;
}
<p id="red">I am a red text.</p>
<p id="red">I am a red text too.</p>
Can anybody explain this strange situation?
Browsers always try to "fail silently". What this means is that even though your HTML is invalid, the browser will try to guess what your intent was, and handle it accordingly.
However, deviating from the spec can cause some very unforeseen side effects.
For example:
document.getElementById('red');
will only get you the first one.
You'll also have to test your page in all the browsers that your users might use, to make sure your code works as intended. You can't just assume that it'll work.
In short: Don't do this! If you need to target several elements with the same CSS, use a class name. That's what they were designed for...
Having said that; if you really need to select multiple elements with the same ID, use an attribute selector:
document.querySelectorAll('p[id="red"]');
Note however, that this doesn't work in IE7 and below...
Is it safe to give several elements the same ID in one page?
As you know, it's against the validation rules to give more than one element the same ID in a single page. However, rules are broken, and in the world of HTML tag soup, browsers have to account for these broken rules without breaking pages, hence the behavior you observe.
Although browsers have been shown to behave the same way even if you do so (fortunately for situations where it can't be helped), I wouldn't call it totally "safe" to do so, as such behavior may not be consistent or reliable.
The best bet is to follow the rules as faithfully as you can, and only break the rules if you have very, very good reasons to (and you almost never will, so don't even consider it). Otherwise, like Joseph Silber said, use classes, designed specifically for classifying or grouping multiple elements.
Can anybody explain this strange situation?
The uniqueness of IDs in an HTML document is not enforced or assumed by CSS; instead, the Selectors spec simply states this:
An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.
Notice the use of the word "an" throughout this sentence.
Following that statement are some example uses, which use the word "any" instead:
The following ID selector represents any element whose ID-typed attribute has the value "chapter1":
#chapter1
The following selector represents any element whose ID-typed attribute has the value "z98y".
*#z98y
The assumption of a conformant document is clarified by level 3 of the Selectors spec, near the beginning of the section (emphasis mine):
What makes attributes of type ID special is that no two such attributes can have the same value in a conformant document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element.
Where "conformant" refers to conformance to HTML, not CSS. Keep in mind that this text wasn't present in the level 2 spec, which is the one you quote in your question.
Bear in mind that the text that is quoted is not normative. While it's a way of helping implementers work out error-handling cases, it's not a compulsory rule to be followed, and indeed, any implementation is free to behave differently without being in violation of the spec. Don't write invalid HTML just to take advantage of what may seem to be expected or consistent behaviors, because you can't guarantee that these behaviors will remain that way. Any CSS implementation is free to match elements sharing the same ID differently, or even stop matching them altogether, if it decides that's how it should handle documents that break this rule.
In other words: just because you can, doesn't mean you should.
This works with simple HTML styling but will not work with queries.
From the jQuery API documentation:
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM. This behavior
should not be relied on, however; a document with more than one
element using the same ID is invalid.

When to use div id or div classes through an entire website

Sorry for this basic over asked question but I feel I have something to add.
I know id's are for elements which are only used once and classes are for elements which use it multiple times. But does this refer to a single page or the site as a whole?
i.e If I were using a wrapper called main-wrapper which is only used once in the page but on every page of the website would this be an id or a class? I've been making them classes throughout this project and am curious if I need to go back and change it all.
ID's and classes are not just about uniqueness and duplications. There is something called Specificity in CSS, so if you read more on specificity, it will say that ID declarations have more specificity score than class rules, thus, it is recommended to use classes wherever you can in your CSS and leave ID's for JavaScript actions.
Also, lets be clear here, CSS has nothing to do with ID duplication nor does HTML. It's JavaScript where you will find issues if you duplicate the ID in your HTML(DOM). So technically you can use duplicate ID's as they are just identifiers for that element(though, HTML validation will yell out an error), but it does cause an issue when you start using those ID's in JavaScript. (Now am not saying that you should use duplicate ID's but just clarifying the basics.)
Talking more over specificity,
#something {
color: red;
}
.something {
color: green;
}
<div class="something" id="something">This will be red and not green</div>
So, the more you make use of ID's, the more specific your CSS gets and at certain stage, you need to write even more specific rules to override the previous ones thus creating more messy CSS.
Base rule, use tag selectors wherever you can, atleast to set defaults or resetting those elements, use classes over ID's, leave ID's if you want initiate a particular EVENT or ACTION via JavaScript, for example, a click event on a button. Using ID's in your HTML helps JavaScript process faster as it will stop looking for another element beyond your first matched element.
In most cases things are referred to on a per page or per document basis.
No ID should be repeated on a single page of a web site. But it's is fine to use the same ID on every page of a site. So you can have a primary div with id="main_container" and use that on each page of your site. But it should only appear once on each page.
A "class" is designed to be used multiple times on each page or on an as-needed basis.

Why are most elements assigned to a class instead of an ID? [duplicate]

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.

Several elements with the same ID responding to one CSS ID selector

Is it safe to give several elements the same ID in one page? For example this often happens, when using some jquery plugins, when you run some slider or gallery twice or more. We know, developers like to give some ID to the html container in order the script works faster.
Let's read w3.org documentation:
What makes attributes of type ID special is that no two such
attributes can have the same value; whatever the document language, an
ID attribute can be used to uniquely identify its element.
But the next example with 2 elements having the same ID works fine in all browsers, though it's not valid:
#red {
color: red;
}
<p id="red">I am a red text.</p>
<p id="red">I am a red text too.</p>
Can anybody explain this strange situation?
Browsers always try to "fail silently". What this means is that even though your HTML is invalid, the browser will try to guess what your intent was, and handle it accordingly.
However, deviating from the spec can cause some very unforeseen side effects.
For example:
document.getElementById('red');
will only get you the first one.
You'll also have to test your page in all the browsers that your users might use, to make sure your code works as intended. You can't just assume that it'll work.
In short: Don't do this! If you need to target several elements with the same CSS, use a class name. That's what they were designed for...
Having said that; if you really need to select multiple elements with the same ID, use an attribute selector:
document.querySelectorAll('p[id="red"]');
Note however, that this doesn't work in IE7 and below...
Is it safe to give several elements the same ID in one page?
As you know, it's against the validation rules to give more than one element the same ID in a single page. However, rules are broken, and in the world of HTML tag soup, browsers have to account for these broken rules without breaking pages, hence the behavior you observe.
Although browsers have been shown to behave the same way even if you do so (fortunately for situations where it can't be helped), I wouldn't call it totally "safe" to do so, as such behavior may not be consistent or reliable.
The best bet is to follow the rules as faithfully as you can, and only break the rules if you have very, very good reasons to (and you almost never will, so don't even consider it). Otherwise, like Joseph Silber said, use classes, designed specifically for classifying or grouping multiple elements.
Can anybody explain this strange situation?
The uniqueness of IDs in an HTML document is not enforced or assumed by CSS; instead, the Selectors spec simply states this:
An ID selector represents an element instance that has an identifier that matches the identifier in the ID selector.
Notice the use of the word "an" throughout this sentence.
Following that statement are some example uses, which use the word "any" instead:
The following ID selector represents any element whose ID-typed attribute has the value "chapter1":
#chapter1
The following selector represents any element whose ID-typed attribute has the value "z98y".
*#z98y
The assumption of a conformant document is clarified by level 3 of the Selectors spec, near the beginning of the section (emphasis mine):
What makes attributes of type ID special is that no two such attributes can have the same value in a conformant document, regardless of the type of the elements that carry them; whatever the document language, an ID typed attribute can be used to uniquely identify its element.
Where "conformant" refers to conformance to HTML, not CSS. Keep in mind that this text wasn't present in the level 2 spec, which is the one you quote in your question.
Bear in mind that the text that is quoted is not normative. While it's a way of helping implementers work out error-handling cases, it's not a compulsory rule to be followed, and indeed, any implementation is free to behave differently without being in violation of the spec. Don't write invalid HTML just to take advantage of what may seem to be expected or consistent behaviors, because you can't guarantee that these behaviors will remain that way. Any CSS implementation is free to match elements sharing the same ID differently, or even stop matching them altogether, if it decides that's how it should handle documents that break this rule.
In other words: just because you can, doesn't mean you should.
This works with simple HTML styling but will not work with queries.
From the jQuery API documentation:
Each id value must be used only once within a document. If more than
one element has been assigned the same ID, queries that use that ID
will only select the first matched element in the DOM. This behavior
should not be relied on, however; a document with more than one
element using the same ID is invalid.

Are the nested ids in css appropriate?

I've been trying to get my own opinion about this issue but could not, so decided to ask.
While it seems to be well-known that the id in html is created to represent the unique element on the page, my experience is that the amount of unique elements on the page is normally quite big, especially in the custom forms. Moreover a lot of unique elements on the page are nested.
Let's take just a simple structure like this:
#content
form#search-filters
#datepicker
#search-results
When it comes to styling this peace of code you have in general two approaches (I am using scss and so are the examples):
Organize it hierarchically, e.g.
#content {
columns(8, 12);
#search-filters {
#include search-filters;
etc.
Go with the plain declarations
#content {
columns(8, 12);
}
#search-fiters {
#include search-filters;
And from my opinion it is damn cooler to have it in the first way, while it's somehow against all the logic.
The question stays even worth with the contents of that #search-filters block, given as the example above. Let's say you've used some Rails scaffolding which generated the id's for each element of the form hosting the filters, and you want to refer to that id's to provide the styling as well.
You know the the element is unique and that it will be unique in any form which extends the search-filters mixin. So you want it to have the id.
But you have to give it a class to make it logically consistent.
What is your opinion about this issue?
P.S. I've tried to read the spec about whether there are some performance difference in these two cases, but it doesn't say anything:
http://www.w3.org/TR/css3-selectors/#class-html
You generally want to have id and class selectors that are not nested, because this gives you the best rendering performance. You can read this in great details at Googles Optimize browser rendering article.
In addition having no nested CSS selectors lowers the specificity and allows you to override it for specific cases more easily.
For simple sites that have a manageable amount of style this may not matter, especially if you also handle the other speed aspects right, like put styles before scripts. In such cases I would prefer the nested style for better readability.
I don't think nesting IDs selectors will make CSS styles apply faster from a browser rendering point of view.
Also, since you already have the ID, using only that ID will make your CSS more easy to read instead of having long selectors chain.
It is different though if you plan to have different styles referencing to the same element, if the element should change it's position along the page, or maybe removed and then later recreated in another position (thus needing different selectors). In this case maybe you will need to have nested selectors, otherwise I don't see the need for that.