Is it bad to have many classes in a HTML element? - html

In modern HTML coding, it is popular to add several class names to an element such as
<div class="class1 class2 class3 class4 ..."
</div>
This gives us a great flexibility for mixing CSS properties without repeating them for different classes.
Logically, the browsers consumes more resources to collect CSS properties of different classes for applying to the corresponding element.
Since it is difficult to run a reliable benchmark on this, I am asking this question from theoretical point of view. Imagine that most of the HTML elements of a page have several classes (e.g. 10 classes). Does this make the page render more difficult and slower? Is this slowdown sensible and considerable?
In general, what is the common process of browsers to read properties from different classes?

The interest in adding many classes, is to have separate classes for individual styles and not repeat/create a new class for the same use.
For instance, if I have a button, I can have 3 classes, like .btn .big .grey. If I want to create another button, I only need to repeat the .btn class, and add my other custom classes, like .medium, and .green. It's called the OOCSS (Oriented Object CSS).
With regard to performance, I recommend you watch this little example http://www.css-101.org/descendant-selector/go_fetch_yourself.php, http://csswizardry.com/2011/09/writing-efficient-css-selectors and you can find a lot of articles about performance on ids vs classes.

Multiple classes can make it easier to add special effects to elements without having to create a whole new style for that element. For example, you may want to have the ability to float elements to the left or right quickly. You might write two classes "left" and "right" with just "float:left;" and "float:right;" in them. Then whenever you had an element you need to float left you would simply add the class "left" to its class list.
I like to use multiple classes for things that I want to keep standard across the entire site. For example, if I always want the bottom-margin for elements that have a bottom-margin to be 10px. By creating a class that only encompases the botom-margin:10px; I can add it wherever it's needed.
Disadvantages of Multiple Classes
While they are supported in the major browsers, really old browsers don't support them. So you should make sure that the first class you list is the one with the most specific information for that element.
Multiple classes can also get really confusing as you apply more and more to an element.
More...
Summary:
Reduce total number of selectors (including IE-related styles: .ie7
.foo .bar)
Avoid universal selectors (including unqualified attribute selectors:
[type="url"])
Page zoom affects CSS performance in some browsers (e.g. Opera)
Window size affects CSS performance in some browsers (e.g. Chrome)
Page reloads can negatively affect CSS performance in some browsers
(e.g. Opera)
“border-radius” and “transform” are among most expensive properties
(in at least WebKit & Opera)
“Timeline” tab in WebKit-based browsers can shed light on total
recalc/reflow/repaint times
Selector matching is much faster in WebKit
http://perfectionkills.com/

Related

Unique stylesheet for embedded content

I have some html markup & css styling that will be embedded on several thousands of different websites. I want this section to only use my own stylesheet, while ignoring the original site's css.
Apart from using unique prefixes for all classes and id's, is there a way to not apply site wide css rules on a certain area, and only use my own styling?
FYI !important declarations in user CSS will always win against CSS Author and User Agent ones (resource: the cascade on Sitepoint), but that's not what you're competing with.
There's no way to only apply your CSS while completely ignoring the rest of the page, afaik (the C in CSS is there for a reason ;) ). But nevertheless, here's a bunch of things that should help:
!important is very powerful. Only other declarations with this modifier have a chance to still be applied
same for inline styles (not sure if it's as needed as it is for those dreaded HTML emails though)
id have a strong specificity. A selector with 412 classes and no id has less specificity than one with 1 id and no class (that's why it's a bad practice according to OOCSS and css linters based on it. Ymmv)
a nice trick allowing to artificially add to CSS specificity is .c.c { prop:val}: twice the specificity of .c {} and exactly the same scope. Imagine this with id ;) (you can also have an id on each and every ancestor of an element but you can't have 2 id on the same element)
initial and unset'd have been nice if it was supported by IE... Would be even better: all property but it's IE11+ and not in Safari
So you'll have to read carefully MDN for each property you want to reset and apply its default value. Or read this amazing answer here on SO on a related question: https://stackoverflow.com/a/18464285/137626
Don't forget about declarations inside Media Queries that could apply on client websites: you (or you clients) won't see them until they resize their browser.
I care a lot about not having not too much specificity in general rules and then specific ones in default resolution, but in that last MQ (320 or 1600+) of a given project, I don't really care anymore if it' more convenient for me (i.e. faster) as I know for sure that I won't need to override it later. Ever.
EDIT: don't forget to take into account pseudos :before and :after. Normalize.css is now declaring *, *:before, *:after { (-prefix-)box-sizing: border-box } and that may be surprising if you also use them. Better not use them imho as they can't be styled in style attribute (same problem with MQ).
To annihilate any style these pseudos could have, this code:
high-specificity-selector *:before,
high-specificity-selector *:after {
content: none !important
}
should be enough: no content, no pseudo.
/EDIT
If you're pretty serious about your project (thousands of websites, wow), you could also automatically test for the CSS applying on client's website in the wild, with tests verifying:
the CSS values of a bunch of properties on a bunch of elements of your widget. Resource: http://csste.st/tools/
the rendering of your widget compared to an initial screenshot with teh mighty PhantomCSS (based on CasperJS, itself based on PhantomJS. Casper tests in WebKit but there are clones testing in Gecko/SlimerJS or with IE/TrifleJS)

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.

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.

Is element-specific CSS selector bad?

Is p.error better or worse than .error?
I have read that element-specific selectors are bad and should be used only if really needed but noone seems to know why. I mean I do understand that .error is better for code reuse, but is there somekinda specific reason why I shouldn't address class with element always?
CSS selectors are read right to left. So p.error has one additional step to .error. This may result in a smaller set or not - depends on your markup.
However, this is a micro micro optimization. There is not going to be a performance hit unless we're talking about a massive amount of selectors.
Here's a great article on CSS selectors that elaborates on how they are evaluated : http://css-tricks.com/efficiently-rendering-css/
.error is more efficient than p.error .
To understand why this is more efficient I recommend you read this article over at css tricks.
no it's not bad, but it may not always be necessary
tools like Google's PageSpeed and YSlow! refer to these type of selectors as being "over qualified" perhaps that's where you're hearing the "it's bad" part from - reading material
take for example p#myid - an ID should always be unique on a page anyway, therefore there is no need at all to qualify it with the p element. an ID already has the highest weight when specificity is being counted so again it's totally redundant to add the extra part to try and add more specificty.
However with class names like your example it can sometimes definitely be desirable to add the qualifier as you may want the class to be re-usable on different type elements but have different properties depending on if it's a div or a p for example, the "qualifier" then makes the selector slightly more specific
.error {background: red; margin: 5px;}
p.error {margin: 2px;}
The code above means you can use the error class on any element and it will have 5px margins however if you set the error class on a p element the second selector is actually doing something, it's over-riding the first's margins but still getting the background color
So they do a job, but too often you see too many people over qualifying all their elements when it is not necessary.. for example if you're only ever applying that .error class to a p element then you wouldn't need the second selector.
The rule of thumb is to make the selector unique as quickly as possible starting from the right side of it.
Having a very specific selector will not amount to bad performance, but if there are a lot of declarations applicable for an element, then the performance will take a hit. The only concern otherwise is that it increases the no. of bytes to be downloaded for loading the stylesheet. Trust me, Every extra character in HTML passed is evil and will amount to lower page load speed.
During CSS cascading is applied by modern-day browsers, the following is the process that occurs for each CSS property for each web page element:
Gather all the declarations for the property from all the sources. This includes default browser styles and custom user style, as well as author style sheets. If there is more than one, proceed to 2.
Sort the declarations by importance and origin in the following order (from lowest to highest priority):
user agent style sheets (default browser styles)
normal declarations in a user style sheet (a user’s custom style sheet)
normal declarations in an author style sheet (web page style sheets; external, embedded, and inline styles)
!important declarations in an author style sheet
!important declarations in a user style sheet
The one with the highest priority wins. If more than one have the same priority then proceed to 3.
Sort by selector specificity. The one with the most specific selector wins. If no clear winner, proceed to 4.
The one that comes last in the source wins!
If the cascade does not set a CSS property on an element, then the browser will fall back to using an inherited property from the element’s parent (this only happens for some properties), otherwise the property is set to the CSS default value.
According to the above process, if you use a lot of more specific selectors, there would be a choice made after atleast 3 levels deep. Hence, the more the no. of declarations which might be applicable to an element, the lower the performance would be.
So, You must as specific as it makes sense to be.
The reason is specificity. For example...
+1 each access by class
+1 each access by tag
+10 each access by ID
etc.
So, if you have a class and a tag access, that style has a specificity of 2 (1+1).
Later, if you're trying to style all .error elements, but you have a conflicting style in the p.error elements, the higher specificity will win. This may cause some headaches down the line. That is why you may not want to always use tag+class.
(That being said, specificity solves many more problems than it creates, and is generally regarded as Pretty Awesome.)
As a general rule of thumb, the less selectors a browser has to evaluate the better.
p.error isn't necessarily "worse" than .error, if .error is used for multiple tags. e.g. div.error (see a foot note at the bottom).
But if it's only used on a paragraph anyway, then having p.error is just making the browser work harder i.e.
First it will have to find all elements with the class attribute error and then filter these by only having tags that are p.
Here is some interesting reading on Optimize browser rendering on Google's Page Speed site.
Foot Note
However if you need to use a class on multiple tags, it's probably best only to put in the css styles which apply to those tags instead of trying to separate it. e.g.
.error
{
color:red;
}
h1
{
font-size:2em;
}
p
{
font-size:0.8em;
}
<h1 class="error">Bad Heading!</h1>
<p class="error">bad!</p>
So that kind of defeats the need to prefix classes with tags anyway.
I hope this helps!

Is not changing the body an HTML/CSS standard?

Often times I see something like this:
<body>
<div class="container">
</div>
</body>
Why not just do:
<body class="container">
</body>
You are perfectly free to do any of the following:
add a class or id attribute to the body element;
directly apply CSS to the body element, with or without class or id attributes; or
directly apply CSS to the html element, although without the class or id attributes and with some important caveats.
Any of these are perfectly legitimate uses of CSS and HTML.
Why <div id="container"/>? Through the years, many CSS techniques have employed arbitrary container elements for conceptual simplicity, to avoid certain cross-browser inconsistencies or because they were simply too complex to be achieved otherwise. A couple of more subtle reasons include that in older browsers, one could not apply CSS to the html element directly, and there were (and are) certain unusual or restricted properties for those elements—often for obvious reasons. (They were sometimes described as being "magic" for this reason.)
These all conspired to create a situation where to achieve almost any moderately complex layout, it was inevitably much easier to just start out with a squeaky-clean container element. Though the practice started as a means to an end it soon became just part of the scenery, and now many developers don't think twice about adding that sprinkling of extra markup.
No, there is nothing that says you can't add a class to the body.
Attaching a class to the body is actually quite common in various CMSes and is very handy for theming or styling specific pages.
From looking at your example, if you just want to use the body as a container, why even bother with the class? There should only be one body element, so just call that in your selector.
Walter, it may make sense if you needed to apply a slightly different subset of styling to a page with a custom body tag.
Using a wrapping div is usually for some presentational reason and make not make sense semantically; if you don't need it for your project, don't use it. Sometimes only using the body tag to contain the page is too inflexible for some layouts, and as Jordan says some old browsers cannot apply CSS to the root element.