div#name vs #name - css

I know that in a stylesheet div#name and #name do the same thing. Personally I've taken to using div#name for most styling I do, with the reasoning that it's slightly faster, and means that I can identify HTML elements more easily by looking at the CSS.
However all of the big websites I seem to look at use #name over div#name (stack overflow included)
In fact I'm finding it very difficult to find many websites at all that use div#name over #name
Is there some advantage to doing #name that I'm missing? Are there any reasons to use it over div#name that I don't yet know about?

Since the div part of div#name is not required (because ID are unique per page), it makes for smaller CSS files to remove it. Smaller CSS files means faster HTTP requests and page load times.
And as NickC pointed out, lack of div allows one to change the HTML tag of the element without breaking the style rule.

Since ID's have to be unique on the page, most ID's you'd run into would only ever appear once in your style sheet, so it makes sense not to bother including what element it would appear on. Excluding it also saves a few characters in your style sheet, which for large sites which get visited millions and millions of times a day, saves quite a bit of bandwidth.
There is an advantage to including the element name in the case where a division with ID "name" might appear differently than a span with ID "name" (where it would show a division on one type of page and a span on another type of page). This is pretty rare though, and I've never personally run across a site that has done this. Usually they just use different ID's for them.
It's true that including the element name is faster, but the speed difference between including it and excluding it on an ID selector is very, very small. Much smaller than the bandwidth that the site is saving by excluding it.

a matter of code maintainability and readability.
when declaring element#foo the code-style becomes rigid - if one desires to change the document's structure, or replace element types, one would have to change the stylesheets as well.
if declaring #foo we'll better conform to the 'separation of concerns' and 'KISS' principals.
another important issue is the CSS files get minified by a couple of characters, that may build up to many of characters on large stylesheets.

Since an id like #name should be unique to the page, there is no reason per se to put the element with it. However, div#name will have a higher precedence, which may (or may not) be desired. See this fiddle where the following #name does not override the css of div#name.

I would guess that including the element name in your id selector would actually be slower – browsers typically hash elements with id attributes for quicker element look up. Adding in the element name would add an extra step that could potentially slow it down.
One reason you might want to use element name with id is if you need to create a stronger selector. For example you have a base stylesheet with:
#titlebar {
background-color: #fafafa;
}
But, on a few pages, you include another stylesheet with some styles that are unique to those pages. If you wanted to override the style in the base stylesheet, you could beef up your selector:
div#titlebar {
background-color: #ffff00;
}
This selector is more specific (has a higher specificity), so it will overwrite the base style.
Another reason you would want to use element name with id would be if different pages use a different element for the same id. Eg, using a span instead of a link when there is no appropriate link:
a#productId {
color: #0000ff;
}
span#productId {
color: #cccccc;
}

Using #name only:
Well the first obvious advantage would be that a person editing the HTML (template or whatever) wouldn't break CSS without knowing it by changing an element.
With all of the new HTML5 elements, element names have become a lot more interchangeable for the purpose of semantics alone (for example, changing a <div> to be a more semantic <header> or <section>).
Using div#name:
You said "with the reasoning that it's slightly faster". Without some hard facts from the rendering engine developers themselves, I would hesitate to even make this assumption.
First of all, the engine is likely to store a hash table of elements by ID. That would mean that creating a more specific identifier is not likely to have any speed increase.
Second, and more importantly, such implementation details are going to vary browser to browser and could change at any time, so even if you had hard data, you probably shouldn't let it factor into your development.

I use the div#name because the code is more readable in the CSS file.
I also structure my CSS like this:
ul
{
margin: 0;
padding: 0;
}
ul.Home
{
padding: 10px 0;
}
ul#Nav
{
padding: 0 10px;
}
So I'm starting generic and then becoming more specific later on.
It just makes sense to me.

Linking div name: http://jsfiddle.net/wWUU7/1/
CSS:
<style>
div[name=DIVNAME]{
color:green;
cursor:default;
font-weight:bold;
}
div[name=DIVNAME]:hover{
color:blue;
cursor:default;
font-weight:bold;
}
</style>
HTML:
<div name="DIVNAME">Hover This!</div>
List of Css selectors:
http://www.w3schools.com/cssref/css_selectors.asp

Related

Is it proper syntax to "nest" id declarations inside other id declarations in CSS?

So, I'm not sure what I've stumbled upon here. I'm working with some CSS and I know it is common place to do something like this:
#content{
/* Style the content div. */
}
#content p{
/* Style all p elements in the content div. */
}
I'd like to give one specific p element a float:right style. Only one such p element will occur in the content element. Naturally, I'd just give this element an id, but then I had the idea to do it this way:
#content #right_floating_p{
float:right;
}
This works when I run the code, but I was wondering about best practice and whether or not this actually does anything scope wise. I could just as easily define a separate id for right_floating_p, but to me it feels natural that it should be defined with the content id because it will be used only on one p element inside the content element.
If anyone has any information about this syntax, please let me know. Thanks!
My recommendation is to only include the last ID. This is fairly standard separation of concerns. What if you want to change the first ID #content, but the last one #right_floating_p still makes sense and shouldn't change? There is more room for error if you specify something unnecessarily.
Other reasons this is good:
Smaller, faster (but barely) download size for your users.
More readable, in my opinion.
Faster (but barely) performance.
Over-qualifying tags is bad practice in general, as far as performance goes. Browsers read your selectors from right-to-left, by the time it interprets your #content selector, that information is pointless. My advice is to not trust that the browser will optimize for this.
Alvaro nailed it in his comment above.
The id must be unique on the page, but not necessarily across the whole site. So, for instance, if you had the #right_floating_p element on every page, but it had a #content element as an ancestor only on a certain page where you wanted it styled differently, then you'd want to use the #content #right_floating_p selector to apply the context-specific style.
I would suggest only using the most precise selector as you can, not only for readability and file size, but also for specificity.
CSS selectors have a specificity to them, so if you were to override it later (such as with a media query), the more specific selector will override the less specific one.
#content #right_floating_p {
color: red;
}
div #right_floating_p {
color: green; /* Will not apply, as it's less specific */
}
p {
color: black; /* Even less specific */
}
It will work having the first selector, but it's not necessary.

CSS: Is it important to specify the exact path for a particular element for speed/accuracy?

When defining CSS for a particular element does specifying exact path make any difference when we are talking about speed/accuracy/processing of a web page?
for e.g. if I have text inputs ONLY in 3rd column of my table, which is better for speed, accuracy, processing and other parameters?
OPTION 1:
table input[type="text"]
{
background:yellow;
}
OPTION 2:
table td:nth-child(3) input[type="text"]
{
background:yellow;
}
No, adding more compound selectors just gives the browser more elements to check and thus more work to do.
If the inputs will only ever appear in a specific place and you can guarantee that they will never appear anywhere else in a given page, then however precise you make your selector beyond input[type="text"] is irrelevant because it will always target the same set of elements anyway. Any extra checks you add then become redundant.
But the real question is whether performance even matters here. Unless you have tens of thousands of such elements, chances are the answer is no. Be as specific as you feel comfortable with. If you need the contextual selectors to make sure you don't accidentally target the wrong elements, there is no harm in putting them in.

Is avoiding duplicate declarations considered good practice in this case?

Is it recommended to combine equal declarations in CSS in order to reduce the filesize and avoiding duplications?
For Example:
#topbar,#searchbox.focus,#usermenu li:hover a,#cart-flyout-table tbody td,.btn_remove:hover,#heading-warenkorb a:hover,.button:hover span,.input-text:focus,#pages li a:hover,select:focus,.picture-overview li:hover,#category-sub li a:hover {background-color:#e3eed3}
Is it recommended to do this for some other Properties which are used very often like float,text-align or padding for example?
The Code would getting harder to read and edit but if this will be done only for the most common properties I would accept it. What's about the performance at the rendering? Would it make my website faster or slower?
The answer is: varies.
In general, I would only recommend on doing that when the elements in question are similar in content or in area. I'll explain.
let's say you have a sidebar, and that sidebar has several headlines in it, which you wish to have similar stylings. That's perfectly acceptable to use aside h1, aside h2, aside h3 { font-weight: normal; color: blue; }.
However, to use it the way you described, for a 100 different elements on different parts of the page, then I won't recommend it.
I would avoid the type of CSS styling you mentioned.
It makes your stylesheets much harder to read and update.
Instead, I would group styles according to sections of the page
nav, header, content, etc.
or by actions
form, call to actions, etc.
or a combo of both.
If you see some duplication within those categories, then combining would be fine.
Otherwise, for example, if you want to update one a, you may need to look in four or more different places (for link, active, visited, and hover).
i can't see any problem in combining declaration.
Yet, if you want to apply the same style to your whole page, you'd better considering calling body { } or * { }.
Details to choose between these two are described here: difference between body and * in css
You may also consider using classes or css inheritance to avoid so many combination

Is there any pros and cons if i use always CSS Class instead CSS ID for everything?

In CSS we can use both ID and class. is there any pros and cons if i use Class always instead ID in terms of Semantic, Web standards- W3C , SEO , Accessibility and future maintainability?
One big difference: in CSS, a class has a lower importance level than an ID.
Imagine that each specification in a CSS declaration added a certain number of points to that declaration's value. Let's say the points go something like this (totally made up, but whatever):
Tag name ('a', 'div', 'span'): 1 point
Class name ('.highlight', '.error', '.animal'): 10 points
ID ('#main-headline', '#nav', '#content'): 100 points
So, the following declarations:
a {
color: #00f;
}
.highlight a {
color: #0f0;
}
#nav .highlight a {
color: #f00;
}
are worth 1, 11, and 111 points (respectively). For a given tag, the declaration with the highest number of points that matches it "wins". So for example, with those declarations, all a tags will be blue, unless they're inside an element with the "highlight" class, in which case they'll be green, unless that element is inside the element with id="nav", in which case they'll be red.
Now, you can get yourself into tricky situations if you're only using classes. Let's say you want to make all the links in your content area blue, but all the links in your foo area red:
.content a {
color: #00f;
}
.foo a {
color: #f00;
}
By my previous (made up) scale, those both have 11 points. If you have a foo within your content, which one wins? In this situation, foo wins because it comes after. Now, maybe that's what you want, but that's just lucky. If you change your mind later, and want content to win, you have to change their order, and depending on the order of declarations in a CSS file is A Bad Idea. Now if, instead, you had the following declaration:
#content a {
color: #00f;
}
.foo a {
color: #f00;
}
Content would always win, because that declaration has a value of 101 (beating foo's 11). No matter what order they come in, the content declaration will always beat the foo one. This provides you with some very important consistency. The winners won't arbitrarily change based on changing orders in the file, and if you want to change the the winner, you have to change the declarations (maybe add a #content in front of the .foo declaration, so it will have 111 points).
So basically, the differences in values are important, and you get a lot of inconsistency and seemingly arbitrary winners if you just use classes.
I know i'm not the 'norm' here and i'll get thumbed down for this... but i use classes exclusively and only ever use ID's for scripting :)
This creates a clear line of seperation of designer and coder related tweaks and changes, which is very handy for us!.
Also we have some .NET web form coders (even though we are moving all sites to MVC) and as .NET controls take over ID's to script them dynamically using ID's for CSS is a pain... i'm not a fan of using #ct00_ct02_MyControlName in css files and even if i was changes to code can break the CSS! Classes works GREAT for this.
Some PHP libs others in the company are using also need to use dynamic ID assignment, this creates the problem here too. again Classes work GREAT here.
As more and more of these dynamic outputs and languages use up the ID's (for exactly what they are really intended for... identifiing an element to work with it) it can be more and more of a pain to work with IDs in CSS.
It's seems to me that everyone wants to use them simply cause they think they should, becuase they are 'there', i offer the idea that ID's are not there at all for CSS and their use in CSS is just there as an extra helper via the selector and their real use is scripting.
There has not been a single instance where i needed an ID for css use or even a single instance where it would have been eaiser.
But perhaps i'm just used to it and thats why? My HTML output is small, my CSS files small and direct. Nested elements work in all browsers as i expect, i dont have issues and can create complicated nicely rendered pages. Changes take mere minutes as i can apply multiple classes to an element or make a new one.
ID's for scripting, CLASS for css... works a treat.
Obivously there is no major issue (Even in a team of designers and coders) in using them both for css as we all get used to what we get used to :) but the way we work it outputs the expected results fast, and noone can step on anyones toes even in anonomous sharing enviroments.
My biggest one would be from the future maintenance point of view. Not only is it nice to know that a style is only used for one element on a page, but if you ever start integrated javascript into your page its nice to be able to access elements quickly using their IDs rather than try and access them by their class's.
If you're using a decent javascript library (like prototype or jQuery) then no, I can't think of any technical reasons why this would matter. However, it might help your own internal thinking and consistency to think separately about whether it is an attribute-like collective characteristic (=> class) or a specific item (=> ID).
Use id when an element is unique on a page and you always expect it to be. Use class when multiple elements will be assigned the value of the attribute. It's true that it may not make a big difference from a purely CSS perspective, but from the JavaScript or Selenium perspective, it's a big deal to be able to uniquely identify elements by their id attribute.
In simple we can define id and class as below
ID = A person's Identification (ID) is unique to one person.
Class = There are many people in a class.
Use IDs when there is only one occurence per page. Use classes when there are one or more occurences per page.There is no hard rule on when to use ID and when to use Class. My suggestion is to use class as much as possible for maximum flexibility, with the only exception being when you want to use Javascript's getElementByID function, in which case you need use ID.
IDs are good for elements that need to be accessed from JavaScript. But the IDs must be unique in the page according to w3 standards, that is:
you cannot have two <div id="Header"> in one document
you cannot have a <div id="Header"> and <p id="Header"> in one document
Class names are good for elements that do not need to be accessed from JavaScript (although it is possible to do so). One class name can be used for multiple elements, and one element can have more than one class names attached to it. Class names therefore allow you to create more "generic" css definitions, for example:
<div class="column">
<div class="column left-column">
<div class="column right-column"> -- all three can be in the same document
You can mix IDs and classes together.
To summarize: use IDs for specific cases; class names for generic cases; and cascad classes for elements that share some general properties but not all.
See following:
CSS Best Practice about ID and Class?
For SEO: It will make absolutely no difference to seo at all.
You should choose names that reflect the semantic content of that section. eg: id="leftMenu" class="footerNotes"
Don't use any underscores in your class and id names (common mistake).
The only difference between classes and ids, except for the fact that an id MUST be unique and a class does not, is that the browser can use an element's id for navigational purposes. For example, this page has a logo with id="hlogo". If you append to this page's url the hash #hlogo, like this https://stackoverflow.com/questions/1878810/is-there-any-pros-and-cons-if-i-use-always-css-class-instead-css-id-for-everythi#hlogo, the browser will automatically scroll to the logo.

CSS 'schema' how-to

How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
There are a number of different things you can do to aid in the organisation of your CSS. For example:
Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc.
Comment your CSS code.
Why not add a table of contents?
Try using a CSS framework like 960.gs to get your started.
It's all down to personal taste really. But here are a few links that you might find useful:
http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/
http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/
http://www.louddog.com/bloggity/2008/03/css-best-practices.php
http://natbat.net/2008/Sep/28/css-systems/
Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:
Make class names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than left, use something like header_links_object2_left.
Use id rather than class only if you know there will only ever be one of an object on a page. Again, make the id unambiguous.
Consider side effects. Rules like margin and padding, float and clear, and so on can all have unexpected consequences on other elements.
If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.
And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.
Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file.
Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend Firebug enough.
The best organizational advice I've ever received came from a presentation at An Event Apart.
Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:
Reset rules (may be as simple as the
* {margin: 0; padding: 0} rule,
Eric Meyer's reset, or the YUI
reset)
Basic element styling; this
is the stuff like basic typography
for paragraphs, spacing for lists,
etc.
Universal classes; this section
for me generally contains things
like .error, .left (I'm only 80%
semantic), etc.
Universal
layout/IDs; #content, #header,
or whatever you've cut your page up
into.
Page-specific rules; if you
need to modify an existing style
just for one or a few pages, stick a
unique ID high up (body tag is
usually good) and toss your
overrides at the end of the document
I don't recommend using a CSS framework unless you need to mock something up in HTML fast. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own "framework" as you figure out what code is shared by your projects over time.
Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.
Cop-out line of the year: it depends.
How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?
My favorite place to go for information like this is CSS Zen Garden & A List Apart.
There are two worlds:
The human editor perspective: Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...
The consumer perspective: The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.
I recommend you to start with a CSS framework:
Blueprint if you like smaller things
or YAML for a big and functional one
There is also a list of CSS Frameworks...
And then bring it in shape (for the browser) with a CSS Optimizer (p.e. CSS Form.&Opti.)
You can measure the Results (unpotimized <-> optimized) with YSlow.
A few more tips for keeping organized:
Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip
Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.
Semantic HTML with good class names can help a lot with remembering what styles apply to which elements.

Resources