Advantages of using attributes over classes - html

What are the advantages of using custom attributes over use of classes. I see that custom attributes are used at more places. New frameworks such as Polymer also makes use of attributes more heavily. I am aware of custom data attributes, but attributes are also used at other places than data attributes. Polymer has attributes such as layout, horizontal, inline etc.
I am looking for advantages/disadvantages in following areas-
use in defining css styles
Query Selectors
Semantics
Thanks in advance.

Attributes have a couple of advantages over classes. Firstly, being able to simply put down an attribute is more readable:
<nav center fullbleed>
vs.
<nav class="fullbleed center">
Attributes are also easier to avoid conflicts when it comes to css selectors: It's easier to make a mistake when using css selectors such as nav .center > #fullbleed . Classes do offer more options, allowing a eprson to swap ids and classes, but this can often become a mess as they have to figure out whether you need to use .strong vs. #strong.

Related

twitter bootstrap good practice for applying classes

I am working on a project using twitter bootstrap.
I wanted to know if it is a bad practice to use our custom class names along with bootstrap classes in the same div or container.
For Eg :-
<div class="container user-profile"> // is this bad practice?
</div>
Should we create another div for class user-profile :-
<div class="container">
<div class="user-profile">
</div>
</div>
Thanks
No, what you are referring to bad practice is not bad practice, especially in light of cluttering the DOM with additional elements.
It is better to add additional classes to an element than to add additional DOM elements each with a new class
There is nothing wrong with adding additional classes to elements, this is how CSS has been created to work. However, you need to be aware that frameworks like Bootstrap rely on their classes for the functionality they offer, so by adding your own you do risk style collision (e.g overwriting a style Bootstrap otherwise was relying on).
With that in mind, Bootstrap uses fairly effective selectors making it unlikely you can so readily override its functionality, but keep it in mind if you're experiencing unexpected side-effects.
DOM elements are there for creating purpose (holding content), CSS is there for creating style, as such, if you are looking to simply add style, dont also add purpose!

Can I use non existing CSS classes?

I have a table where I show/hide a full column by jQuery via a CSS class that doesn't exist:
<table>
<thead>
<tr>
<th></th>
<th class="target"></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
<tr>
<td></td>
<td class="target"></td>
<td></td>
</tr>
</tbody>
</table>
With this DOM I can do this in one line via jQuery: $('.target').css('display','none');
This works perfectly, but is it valid to use CSS classes that aren't defined? Should I create an empty class for it?
<style>.target{}</style>
Are there any side effects or is there a better way to do this?
"CSS class" is a misnomer; class is an attribute (or a property, in terms of scripting) that you assign to HTML elements. In other words, you declare classes in HTML, not CSS, so in your case the "target" class does in fact exist on those specific elements, and your markup is perfectly valid as it is.
This doesn't necessarily mean that you need to have a class declared in the HTML before you can use it in CSS either. See ruakh's comment. Whether or not a selector is valid depends entirely on the selector syntax, and CSS has its own set of rules for handling parsing errors, none of which concern the markup at all. Essentially, this means HTML and CSS are completely independent of each other in the validity aspect.1
Once you understand that, it becomes clear that there is no side effect of not defining a .target rule in your stylesheet.2 When you assign classes to your elements, you can reference those elements by those classes either in a stylesheet, or a script, or both. Neither has a dependency on the other. Instead, they both refer to the markup (or, more precisely, its DOM representation). This principle applies even if you're using JavaScript to apply styles, as you're doing in your jQuery one-liner.
When you write a CSS rule with a class selector, all you're saying is "I want to apply styles to elements that belong to this class." Similarly, when you write a script to retrieve elements by a certain class name, you're saying "I want to do things with elements that belong to this class." Whether or not there are elements that belong to the class in question is a separate issue altogether.
1 This is also why a CSS ID selector matches all elements with the given ID regardless of whether the ID appears exactly once, or multiple times (resulting in a non-conforming HTML document).
2 The only situation I'm aware of where an empty CSS rule like that is necessary is when some browsers refuse to apply certain other rules properly as the result of a bug; creating an empty rule will cause those other rules to be applied for some reason. See this answer for an example of such a bug. However this is on the CSS side and therefore should have nothing to do with the markup.
There are no ill effects to use classes which don't have styles. Indeed, that's part of the usefulness of CSS is that it's de-coupled from the markup and can style or not style elements/classes/etc. as needed.
Don't think of them as "CSS classes." Think of them as "classes" which CSS happens to also use if it needs to.
According to HTML5 specification:
A class attribute must have a value that is a set of space-separated
tokens representing the various classes that the element belongs to.
... There are no additional restrictions on the tokens authors can use in
the class attribute, but authors are encouraged to use values that
describe the nature of the content, rather than values that describe
the desired presentation of the content.
Also, in the version 4:
The class attribute has several roles in HTML:
As a style sheet selector (when an author wishes to assign style
information to a set of elements).
For general purpose processing by
user agents.
Your use case falls under the second scenario, which makes it a legitimate example of using a class attribute.
You can use a class which has no styles, this is entirely valid HTML.
A class referenced in a CSS file is not a definition of a class, it is used as a selector rule for styling purposes.
When you use a classname in JavaScript, it does not look at the CSS to find that class. It looks directly in the HTML code.
All that is required is that the classname is in the HTML. It does not need to be in the CSS.
In fact, many people think it's actually a good idea to keep separate classes use with CSS and Javascript, as it allows your designers and coders to work independently without getting in each other's way by using each other's classes.
(note, the above paragraph is obviously more applicable for larger projects, so don't feel that you have to go to this extreme if you're working on your own; I mentioned it to make the point that the two can be entirely separate)
You can use CSS classes without using it, but I suggest that if you are adding CSS classes just for the JavaScript/jQuery code, prefix with it js-YourClassName so the front-end developers never use these classes to style the elements. They should understand that these classes can be removed at any time.
The moment you add the Class in your HTML the Class will be defined, so your solution is completely fine
It's not necessary to define CSS classes in your stylesheet. It should work just fine. However, adding it won't harm.
One thing that nobody here has fully mentioned is that JavaScript (aided by jQuery in this case) isn't able to directly modify a document's cascading style sheet. jQuery's css() method merely changes the matched set of elements' style property. CSS and JavaScript are completely unrelated in this aspect.
$('.target').css('display','none'); doesn't change your .target { } CSS declaration at all. What has happened here instead is that any element with a class of "target" now looks something like this:
<element class="target" style="display:none;"></element>
Are there any side effects caused by not pre-defining a CSS style rule? None whatsoever.
Is there a better way to do this? Performance-wise, yes there is!
How can the performance be improved?
Rather than directly modifying the style of each element, instead you can pre-define a new class and add that to your matched elements using addClass() (another jQuery method).
Based on this pre-existing JSPerf which compares css() with addClass(), we can see that addClass() is actually much faster:
How can we implement this ourselves?
Firstly we can add in our new CSS declaration:
.hidden {
display: none;
}
Your HTML would remain the same, this pre-defined class is simply in place for later use.
We can now modify the JavaScript to use addClass() instead:
$('.target').addClass('hidden');
When running this code, rather than directly modifying the style property of each of your matched "target" elements, this new class will now have been added:
<element class="target hidden"></element>
With the new "hidden" class, this element will inherit the styling declared in your CSS and your element will be set to no longer display.
As is mentioned by so many others, yes, using classes with no assigned CSS is perfectly valid and rather than thinking of them as 'CSS classes' you should simply recognise the semantics of class and ID to be groups and individual elements respectively.
I wanted to chip in as I felt an important point hasn't been raised given the example. If you ever need to do visual manipulations to a variable length of elements (in this case you're using table rows) then it always makes sense to recognise that the cost of doing so through Javascript could potentially be very expensive (e.g if you have thousands of rows).
In this situation let's say we know that column 2 always has the potential to be hidden (it's a conscious function of your table) then it makes sense to design a CSS style to handle this use case.
table.target-hidden .target { display: none; }
Then rather than using JS to traverse through the DOM finding N elements we simply need to toggle a class on one (our table).
$("table").addClass("target-hidden")
By assigning the table an ID this would be even quicker and you could even just refer to the column by using the :nth-child selector which would reduce your markup further but I can't comment on efficiency. Another reason for doing this is that I hate inline styling, and will go to great lengths to eradicate it!
It will have no effect if you apply a class on a HTML element, and that class is not defined in CSS. It is a common practice and like Aamir afridi said if you are using classes for js only purpose, it is a good practice to prefix them with js- .
It is not only valid for calsses, but also for id attribute of html elements.
There's no problem at all of using classes to just query for elements. I used to give such class names the sys- prefix (for example, I'll name your class sys-target) to distinguish them from classes used for styling. This was a convention used by some microsoft developers in the past. I also noticed a growing practice of using the js- prefix for this purpose.
If you are not comfortable with using classes for purposes other than styling, I recommend using the Role.js jQuery plugin which allows you to achieve the same purpose using the role attribute, so, you may write your markup as <td role="target"> and query for it using $("#target"). The project page has good description and examples. I use this plugin for big projects because I really like keeping classes for styling purposes only.
Refer to the jQuery validation engine. Even in there we also use non-existent classes to add validation rules on the HTML attributes. So there is nothing wrong in using classes that are not actually declared in a stylesheet.

HTML5 JQuery Selectors

I have always disliked using ids and classes as selectors for obvious reasons: ids are unique and classes have to do with styles and should be able to change without affecting functionality of the site.
I used to create things like
<div rel="foo">...</div>
$("[rel=foo]").click(..);
What is the proper way to do this with HTML5? I was tempted by role, but it appears, this attribute has a specific meaning and purpose.
I am just learning HTML5 and your help is greatly appreciated!
You can add any number of classes to your element. And when you selecting, you can use one class as selector.
<div class="class1 class2 foo">
selector,
$(".foo").click(..);
you don't need to defined foo class inside your CSS
Try not using rel, choose title instead. Then you can use jQuery like this:
$('div[title="foo"]').click(...);
Using title, id or class is proper for HTML5. Also, I think you should revisit using classes and IDs as selectors - it's very handy, efficient and easy.
Don't go against the wildly accepted solution here: use the class attribute.
Try to elaborate a naming convention that maps the structure of your pages and components in these pages.

Using element IDs/class names over other CSS selectors

To what extend should I be attempting to use other CSS selectors instead of element IDs/class names or vice versa.
For instance: body > header nav ul+ul { ... } when I could just do #socialnav { ... } to achieve the same thing.
Example HTML code being (obviously there are headers with child navs elsewhere in the code):
<header>
<nav>
<ul>...</ul>
<ul....</ul>
</nav>
</header>
What is the consensus on this? I mean, I find it manageable doing it using CSS selectors, but is there a disadvantage?
Your first guiding principal should be to keep the markup semantic. Your markup above is a great example of this - you're using header, nav, and ul tags in semantically meaningful ways.
Your second guiding principal should be to maintain separation of concerns (e.g., content and presentation). If adding a class names or id's to your markup does nothing for you semantically and you're able to craft CSS selectors w/out them, then you should avoid adding extra noise to the markup.
Sometimes, however, class names and id's are very useful (not just in CSS but also in JavaScript), so they have their place. Just don't resort to them if they're unneeded and are therefore adding unnecessary clutter to your markup.
It's up to your preferences.
I find it not wise to use body > header nav ul+ul, because a small change in your document structure, and you have to rewrite the CSS selector.
Use .classselectors and #id-selectors for elements which aren't an incredible important part of the main document, and use #one-special-item > ul > li > a:hover span to select the more specific elements.
Generally I try and avoid ID selectors in CSS.
I find it a lot easier to deal with classes than using IDs.
IDs can cause issues later on down the line if the markup is used in a Server-Side application, such as ASP.NET, where the IDs are rendered as something different to how they display in the markup.
However, ID selectors do take priority over class selectors:
http://jsfiddle.net/wcLrF/
You should write your stylesheets as rule sets for your site.
If you are writing a style which is you want to to work with a single specific piece of content, then it is good practice to reference that element's ID.
If you are writing a style which is part of your general site look and feel, then it should be written to reference tagnames and/or classes as much as possible.
There will be times when the actual html code is such that it becomes hard to follow those rules, but if you try to stick to that in general then you'll be okay. You may also need to bend your rules if you need to support older browsers (cough, IE, cough) that don't support all the CSS features that you'd normally want to use.
So yes, I would say that the way you've done it in the question is the recommended approach.
Using IDs and Classes as selectors is much faster than using normal css selectors. Some also argue that you should ONLY use classes because they encourage reusability in your stylesheets.
Here's a really good article about Object Oriented CSS: http://coding.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/

Object oriented CSS

I watched this presentation about object oriented css, but I think I either don't understand it correctly or don't understand the benefits of using OO CSS:
Example HTML:
<div class="border-1 bg-2 color-1 font-1">
</div>
Example CSS:
/* borders */
.border-1 { border: 1px solid red; }
/* backgrounds: */
.bg-2 { background: yellow; }
/* other sections */
I see an advantage in being able to change styles for multiple elements quickly, for instance, being able to switch the color scheme would be very useful.
But actually, you're defining the style/look inside the HTML, or at least a part of it. Of course, it's better than using the style attribute, because you still are able to exchange the styles for a set of groups.
The point is, you are defining the style-groups inside the HTML, but I learned that you should create "logical" groups inside the HTML (e.g. class="nav-item" / class="btn submit-btn") and the CSS completely applies the style and defines which elements belong together from the "stylistic" point of view (e.g. .nav-item, .submit-btn { background: red; }).
Maybe I totally misunderstood the concept. However, I still don't know a good way of constructing my CSS.
CSS isn't object oriented. My suggestion is to forget what you've read about "object oriented CSS" and instead focus on the problems with CSS you're trying to solve. If they are to make CSS easier to write, read and maintain, or to get more features (like CSS variables) I think Less or Sass will suit your need much better.
Using CSS like what's suggested with "object oriented CSS" just leads to terrible, non-semantic and meaningless CSS that in the long run isn't any easier to maintain than "ordinary" CSS. Both id and class should have semantic and meaningful names, so using a framework that allows you to write semantic CSS (that describes intent instead of presentation) is in my humble opinion much better.
This is more of a "name dropping", that an actual method.
The code that you have shown is often derogatory called "enterprise css", there is no excuse for it.
More over, having multiple classes on elements actually hurts performance.
I advice you to adhere to Mozilla's guidelines when making your CSS, which works same for other browsers, too.
And make dedicated .css file with hacks for IE6, 7 and 8.
The idea is that you reuse the same css classes on many elements. This both saves on writing css and on maintaining css. so instead of defining .create-button .cancel-button .create-and-new button you would just have a .button that defines padding, size, background, color, line-height, font-size, font-family and font-weight. And some really small classes for the different button styles like to change the color or font-size
a proper oocss project I often still use can be found here: https://github.com/stubbornella/oocss/wiki
but yes you should have a look at less, it combines the easy of reusing the same css properties on multiple elements with proper class names.
"Object-oriented CSS" is really just a design pattern for how to get most out of your CSS and is basicly the same approach Jonathan Snooks calls SMACSS.
Whether you call it OOCSS or SMACSS, the key to the approach is that you create generic UI elements like the nav abstraction. These UI elements can then be enhanced with more specific features by adding extra classes to the element and/or a container element. Or, as an alternative, you can add your own custom CSS rules using the element's ID or semantic classes.
Further reading :
An Introduction To Object Oriented CSS (OOCSS)
OOCSS + Sass = The best way to CSS