Example you need to float a bunch of elements.
Option 1 - Chain elements
#elm1, #elm2, #elm3, #elm4 {float:left}
Option 2 - Add a similar class to elements
.float {float:left}
Option 3 - Add style to class individually
#elm1{float:left}
#elm2{float:left}
#elm3{float:left}
#elm4{float:left}
I prefer 1 but I don't know how much of a speed impact it has, are there any other options? Whats the convention for this?
http://css-tricks.com/efficiently-rendering-css/ Seems to say that IDs are the most efficient, although IMHO I would think the class is cleaner and more accurately represents what you are trying to express.
From Google's article # http://code.google.com/speed/page-speed/docs/rendering.html#UseEfficientCSSSelectors
"Avoid a universal key selector.
Allow elements to inherit from ancestors, or use a class to apply a style to multiple elements."
So, I think best practices says use a class. Its clean and readable IMHO.
Use option two (classes) for the global cases. That's what class selectors are meant to do.
Use the ID for styling specific differences. This is what ID selectors are meant to do.
.myclass {
float:left;
height:10px;
}
#elem2 {
height:69px;
color:#ABCDEF;
}
The whole purpose of css is to free html from presentation. Thus the semantic approach is always the good one.
If you use .float { float:left } you might as well use style="float:left"... (okay this is an exageration, but the point is that the less style classes you use the better the separation between presentation and information)
As previously mentioned, the best approach is to semantically identify and classify your html code and then use DOM relationships
#elements {
float:left;
}
#elements li {
color:#ABCDEF
}
#elements li.odd {
color:#123456
}
Most CSS minimizer and "cleaners" will do your first option. In my opinion, it's much better than creating a new class to add to a bunch of elements just for style and it's a million times better than your last option.
In CSS, if it already has an ID or a class, you can apply style to it. So, comparing option 1 to option 2, option 1 should be your better choice. You don't have to go back through your code and add classes to elements that already have IDs and you don't have to juggle style between the ID and the class for the same element in your stylesheet.
As far as speed is concerned, I don't think there is much difference between the 3 options. I think it's more of a maintainability question. It seems like option 1 is going to be easiest to maintain of the options so that's probably what I would go with.
There are certain trade-offs involved. Generally, anything ID-based is believed to be faster, especially as the pages grow heavier. On the other hand, http://net.tutsplus.com/tutorials/html-css-techniques/object-oriented-css-what-how-and-why/ and similar article authors believe that using classes for common rules makes sense and should be used. The speed difference is often negligible and carefully used classes make maintaining and updating design a lot simpler.
Related
When I studied front end dev at the university a few years ago, our teacher taught us to always provide the full (almost) parental
DOM hierarchy of the targeted element within our CSS selectors.
So in our web projects we had to write selectors like:
div#container div#content p.bread a.external { }
instead of just:
#container #content .bread .external { }
or (I see the disadvantages with class conflicts that may occur here)
.external { }
I personally write my selectors like
#container #content p.bread a.external {}
until I recently read an article saying that it should be avoided (but with no obvious reason why) and another article saying the same but that one was intended for jQuery selectors.
Was my teacher wrong and what is the right (fastest to parse and with most support) way of writing CSS selectors?
Practically speaking, you should use the least specific selectors you can.
div#container div#content p.bread a.external { } is a very, very specific selector. It is unnecessarily specific. There can only be one #content element, and it will surely always be within #container.
Write general rules. Don't attempt to target the precise DOM element. If a.external will capture the set of elements you want, use that. Otherwise you'll end up having to write p.bread a.external, p.potato a.external, p.olive a.external, etc, etc.
The difference in performance will be minimal. The benefits of general, reusable rules are large.
My 2 cents
Specific enough to target only what needs targeting (as others have said) is the general rule.
I agree with lonesomeday that "difference in performance will be minimal," but every added element in the chain is one more check to be done.
So Think About How to Reduce It
Are the ID's needed?
I disagree with Spudley that "there should never be a need to specify more than one ID in a selector." If your site is set up to have different display on different pages, and so #page1 #content is different than #page2 #content for displaying, then that is a legitimate case of two id's in one selector. However,
If all pages are #container #content then the drop the #container.
Also, if all p.bread elements are inside #content, then drop that selector also.
Are element names needed?
Is .bread intended to be used on anything other than a p? If not, drop the p.
Is .external intended to be used on anything other than an a (probably linking to an external site)? If not, drop the a.
Is the decedent relation of classes needed?
Is the .bread .external significant for display? That is, does .external exist outside of a .bread parent and does it change because of that parent? If so, then keep the relation. Otherwise, if the important thing is only the .external (no matter where it is), then that is the only selector you need.
Yes, your teacher was wrong.
From your example:
div#container div#content p.bread a.external { }
Given that an ID in a DOM document must be unique, there should never be a need to specify more than one ID in a selector. So the above selector that contains both #container and #content is immediately wrong simply by that criteria.
An ID is the most efficient and direct way to reference an element. Again, it's unique and instantly accessible, so there's no need to qualify it in any way, so adding div in front of either of the #container or #content here is redundant.
The other two parts of the selector p.bread and a.external are likely to be wrong, but it's not so clear-cut for these.
A selector only needs to specify the parts that are necessary to select the elements required and exclude any elements that are not required. In this example, if all .bread elements are ps or all .external elements are as then the element type a or p would be redundant and should be dropped. But without seeing your actual HTML content, it's not possible to be certain of this in the way that it is possible for the IDs because a given classname can legitimately be applied to multiple elements of multiple type.
Longer selectors such as div#container div#content p.bread a.external { } do take longer, yes. But rarely do they make any noticeable impact on the paint time.
Also, since IDs are (supposed to be) always unique, div#container and div#content should really just be #container and #content, respectively.
Elements are superfluous (or rather should be) when used with ID selectors (#), since your DOM should contain only unique IDs for elements.
It's also worth noting that classes should be used to bunch the styles of the same elements. In case you have two .bread elements in your DOM, but want them styled differently, you should consider using a different class name.
Both ways will work, and the impact on speed will probably be minimal. However there is no need to add the element to your rule, and I would encourage you not to as it helps your rules become more reusable - something you should always aim for.
You should also avoid using location to target elements. E.g. .sidebar h3. Instead, add a class to those h3s and target the class. This means you can reuse those styles you wrote elsewhere, just by adding the class. These are all concepts of Object Oriented CSS, and will help you write more efficient CSS by reducing the amount of duplicate code.
Which of the following would be considered best (i.e. better) practice?
#anElement {
font-size:1em;
color:white;
}
/* other stuff */
#anElement {
width:100px;
margin-bottom:10px;
}
or
#anElement {
background-color:black;
color:white;
font-size:1em;
margin-bottom:10px;
}
In other words: should I dry the CSS as much as possible or should I work on typography and general layout separately, maybe even in separate files?
Combine them but give the properties a logical grouping. There are several ways to group them; you might order them alphabetically or logically (text properties together, margins-paddings together, etc).
See CSS Property Order, written by Mark Otto, Creator of Bootstrap.
Also worth noting, in a simple styling example like the one you provided you should ask yourself one question...is it possible that some/all of this code might be reused in other spots on the page? Maybe there are several divs that could use the same styling. Then you should be using a class not an id.
The first option is perfectly acceptable, and certain CSS minifiers will combine them all into one anyway. I'd definitely look into using a minifier, since the first option can produce much more readable/maintainable code, especially if separated into multiple files.
Having multiple style sheets is going to hurt your page performance. If you want to organize your css in this way, consider a pre-processor such as http://sass-lang.com/.
I want to know, what does the following CSS mean?
.twoCol #sidebar
Isn't #sidebar alone enough? What does this line of CSS actually select?
This is accessing the element with the id sidebar within any element that uses the twoCol class.
#sidebar is enough on its own really, as it's an ID, but this is a little more semantically correct.
Isn't #sidebar alone is enough?
Yes. An id should be unique. (and it will be, unless you're dealing with poor quality HTML)
The .twoCol prefix is not optimal because it's adding redundant information.
This is comically demonstrated here: http://www.css-101.org/descendant-selector/go_fetch_yourself.php
A more complete article, which isn't specific to this case, but a good and relevant read nonetheless:
http://css-tricks.com/efficiently-rendering-css/
Demian and thirtydot are largely correct, but this does have a conditional use:
If you have several templates and sometimes #sidebar occurs in .twoCol, but sometimes it occurs somewhere else - you can target that specific template without including another CSS file.
In this case, it makes more sense to assign a class to the <html>, <body>, or template wrapper, but I just thought I'd point out that it's not strictly useless.
I'm trying to find out what is the best practice for naming and casing css classes and ids, especially multiple word names.
So for instance, say I have a <div> that I want to name "character skills".
It seems like there are 3 choices: "characterskills", "character_skills", or "character-skills".
Which one of these is the industry standard for naming css classes and ids?
What's the best practice for splitting multiple words in css names?
Also is it a best practice to always use all lowercase for css names, because they are case-insensitive?
I tend to use the hyphenated style as well. I mainly use that style since CSS properties follow the same casing. Similarly, JavaScript functions and variables tend to use lower camel case. For example, to change a CSS property in JavaScript, you would type object.style.textDecoration, but in CSS, that property would be changed with text-decoration.
I use lowerCamel for class names and UpperCamel for IDs. This is quite important and I'm beating this old answer because IMO the hyphenated style should be discouraged, even underscore is better than hyphenated.
Why? Because every other language can't have hyphenated variable names. For e.g., your IDE may or may not pick up auto-completion properly. (My IDE can't, it's VI :P)
CSS being closely related to JavaScript, hyphenated classname also make it difficult to interop with JavaScript. Consider the following (contrived) jQuery:
// For each of the following class, perform a function
var funcs =
{
main: function(){ /* ... */},
toolbar: function(){ /* ... */ },
// Oops, need to use a quote because there's this hyphenated name
'customer-info': function(){ /* ... */ }
};
// Woot, a O(n^2) function
for(var className in funcs)
{
var func = funcs[className];
// maybe if we named it $('#some-selector')? The hyphen suddenly feels
// like some kind of operator to me. Makes me nervous :/
$('#SomeSelector div').each(function()
{
if($(this).hasClass(className)) func();
});
}
There's no clear advantage to using the hyphenated style other than subjective aesthetics. The disadvantages are that it stands out from every other programming language (OK, CSS may not be a programming language, oh well..) and that it is technically incorrect.
The correct (huh?) way to represent a space is underscore. Consider this phrase "a self-addressed letter," how can I convert the spaces?
a_self-addressed_letter (correct, preserves the original meaning)
a-self-addressed-letter (ouch! if we convert it back we get "a self addressed letter"!)
Also is it a best practice to always use all lowercase for css names, because they are case-insensitive?
I guess in this case, it's a best practice to always use PascalCasing because it aids readability.
I personally use the hyphenated style (i.e. some-class) but you should simply choose what you feel is best and be consistent. It is purely an issue of aesthetics.
I see the following casing styles a lot:
characterSkills,
CharacterSkills
But, at the end of the day it doesn't matter which style you pick. Just be consistent within your own app.
I've seen several different answers to this question, depending on who you ask. Ranging through all of the possibilities you mentioned and probably more. The one I see referenced most often, however is to use underscores (character_skills) and all lowercase.
The one answer thats always mentioned though and arguably more important than which method you choose, is to pick one and stick to it throughout. Keeping things uniform throughout allows you to avoid confusion and other problems later.
I use lowerCamelCase for classes, and UpperCamel for IDs, like so:
#HeaderLogo { ... }
.pullQuote { ... }
But it really makes absolutely no difference so long as you're consistent :) Oh, and try to stick to one-word class names where possible - you can always combine classes, like so:
.boxout { border: 1px solid; padding: 10px; }
.emphasised { font-weight: bold; }
.subtle { font-size: small; }
.boxout.emphasised { background: yellow; }
.boxout.subtle { color: gray; }
...which I prefer, as you can have your "base" classes hold core definitions, keeping your CSS smaller, and reducing the overall number of classes you have to remember when designing pages.
After reading examples and making my own mistakes, I landed on this solution for myself:
Use hyphens to show hierarchy e.g. #products-MainContent {} or #maincontent-Summary {}. To me this means that MainContent is a child of the products div.
Capitalise each word after the first element in the heirarchy for IDs. Use all lowercase for classes e.g. #summary-Statistics (ID) or .summary-statistics (class)
This works for me for now. I don't want to use hyphens to separate words because I think hyphens should show dependency/relationships. Also I don't want to mix up IDs and Classes because they look similar so I changed the case in which they were written.
I recommend using the BEM (Block Element Modifier).
Retrieved from its website:
BEM — Block Element Modifier is a methodology that helps you to create
reusable components and code sharing in front-end development.
For more details please visit its website documentation:
http://getbem.com/naming/
I am finding it useful to define 'marker' css styles such as 'hidden' or 'selected' so I can easily mark something as hidden or selected - especially when using a tag based technology like ASP.NET MVC or PHP.
.hidden
{
display:none;
}
.newsItemList li.selected
{
background-color: yellow;
}
I don't especially feel like reinventing the wheel here and wanted to know what other things like this are useful or common - or if there are any pitfalls to watch out for.
Should I look at any specific css frameworks for other things like this? Plus is there a name for this type of css class that I can search by.
I agree with the other posters who say only to define what you need, rather than bloating your code with a bunch of unnecessary classes.
That being said, I find myself using the following on a constant basis:
.accessibility - visually hide elements, but keep them intact for screenreaders and print stylesheets
.clear - tied to Easy Clearing
.first-child and .last-child - easily assign styles to the first/last item in a container. This has been a lifesaver many times, and I prefer it over the poorly-supported :pseudo selectors
.replace - tied to Phark IR for transparent image replacement
Finally, I dynamically assign .js to the <html> element with
<script type="text/javascript">if(h=document.documentElement)h.className+=" js"</script>
This will allow me to define .js (rest of selector) styles to target only browsers with JavaScript enabled.
Let me give you an answer from a very novice web developer who has recently considered using CSS classes as "markers". Please don't take this as a definitive answer, as I may be completely wrong, but look at it as another point of view.
I was going to use some marker classes, too. I created one called .center to center the elements in a DIV tag. However, I was struck with the idea that I'm looking at CSS all wrong. I reasoned that CSS is supposed to define how an element is to be displayed without having to change the HTML page. By using marker classes, like .center for example, I would have to change BOTH the CSS and HTML if I wanted that DIV tag to be right-justified next month. So instead, I created a .latestHeader class (the DIV is to hold the "latest information" such as a news item), and in that class I set the text to align center. Now, when I want to change the justification of the text, I simply change the CSS for that DIV and I don't have to touch the HTML.
In regards to your question about CSS frameworks...
Personally I've always found the W3C has the most complex but also most accurate answer to any CSS question.
After many years of programming and playing around with CSS/HTML/PHP I agree with the above comment.
There is no harm in defining a marker for something to be centered or right-aligned using something along the lines of a '.center' or '.righths', but keep in mind as above that if you want to change a whole slab of text your work will be increased because you have to edit both CSS and HTML.
Defining the format for a whole section will mostly likely work out more logical, because if you want to change the section months down the trail, you just have to edit the format of one CSS declaration as opposed to editing each individual article.
CSS was however designed as the ultimate styling language which could allow an administrator to make a website look exactly what they want it to. Keep in mind though that excess CSS will increase the load on a server, will increase the time before your client sees your page and in line with the 'feng shui of web design' it is possible to go overboard with too much styling.
You should really grow this list on a need basis instead of soliciting a list of generic classes across the board--you'll only end up with bloat. If you want to avoid reinventing the wheel the look into some CSS frameworks (blueprint or 960). In some respect, generic classes like .center { text-align:center } do have some level of redundancy but often times they're needed. For example the following pattern which is all too common but should be avoided:
element.onclick(function(e){ this.style.backgroundColor = 'yellow' }
That's bad because you really ought to be using:
element.onclick(function(e){ this.className = 'highlight' }
The latter allows you to modify your styles by only touching the CSS files. But if a CSS class name has only one style element then you should probably avoid it because it doesn't make any sense to have it (.hidden in your example) and call it directly instead:
element.onclick(function(e){ this.display = 'hidden}
I often find myself keeping two classes in all of my stylesheets: "center" (which simply applies text-align: center;, and a float-clearing class that applies clear:both;.
I've considered adding a "reset" statement to all my styles, but haven't had a need for it yet. The reset statement would be something similar to this:
*
{
margin: 0;
padding: 0;
}
I reuse these often enough to include them in just about everything. They're small enough so I don't feel they bloat the code at all.