I'm coding a landing page. When should I use an ID for an element instead of a class? I know IDs are only referred to once on a page, while classes are referred to multiple times. I also know using a class is faster than using an ID. When should we use a class over and ID for an element?
Simply put, ID's are for JavaScript, classes are for styling (CSS). You can use Id's for styling still however, where needed. But in general, you should work towards using CSS classes and re-usable code.
Some people also follow a convention of using ID's for chrome elements on their site. Myself, I use classes for everything to allow for future code re-usability. I can't tell you how many times this has made life easier 6 months down the track. If I need to target something with JavaScript, then I also add an ID.
Performance
JavaScript
Id's are faster than classes when referenced in JavaScript.
CSS
Performance depends on the individual browser rendering engine.
Best Practice
Check out this handy guide on MDN that teaches you to write efficient CSS.
Related
Why do I see .closed-dialogue and .open-dialogue so often in commonly-used libraries, instead of .closed.dialogue and .open.dialogue?
the problem with a single class per element
To format all dialogues with the first approach, you would already need two classes in the selector.
Each time you add another difference, f.e. some colour, you would multiply the number of classes in the selector: .warning-dialogue-closed, .error-dialogue-closed, .warning-dialogue-open, .error-dialogue-open.
Now how can that be good practice? This is hardly maintainable!
You couldn't even separate your code in modules, since the basic selector for dialogues needs to know all dialogues that exist!
several classes per element solve this
By concatenating several classes, the code would be way shorter, more maintainable and easier to read:
.dialogue formats all dialogues, no matter how many different you have.
.error.dialogue and .warning.dialogue would add changes for either flavour. .open.dialogue and .closed.dialogue would take care of the other difference.
You even could have another isolated module that defines big and small dialogues, and the basic module doesn't even have to know about it.
So why have I never seen this?
The problem with your approach is that it's more likely to conflict with other classes.
If the page itself has some other unrelated open class, class="open dialog" will pick up rules for that class and get messed up.
This is why libraries like jQuery UI tend to prefix all of their classes with a unique value.
I've read this
Why selecting by ID is not recommended in CSS?
which presents arguments for why you would use classes instead of ID's. And many dev's go cold turkey and refuse to use ID's at all for style selectors.
But, I'm sure many if not most experienced devs still use ID's as stylistic hooks(while favoring classes).
What are some possible scenarios that might justify using ID's instead of classes?
You may use ids when you are targeting unique items (you don't want to reuse that particular style) like #header,#footer.
Another good reason to use ids may be if you're a front-end developer thattakes care of some basic javascript too. Javascript access to elements via id is a lot faster than by other chained class names, so for performance reasons , you (as a js developer) might want add an id to your widget that allows you to access that element a lot faster.
For example
#widget
is faster and easier to access through js than something like
.wrapper .container .sidebar .widget:nth-child(n)
From what I've found, people (not all, but most) that try to only use class and attribute selectors make a mess of their style sheets. They end up putting a class on everything and then have long selector strings trying to move one certain element, which is where ID selectors shine. ID's were implemented into CSS for a reason and they are great when used properly.
Just use sparingly.
Here's the situation. It can't be changed, I have to deal with what I have.
I have a few pages of which I have styled inside a wrapper, two columns of various content.
I was given (after my pages were done) a shell which I now have to integrate the content. I wasn't to do this in the beginning; I was told to build and style as if these pages lived on their own.
So, now I have to essentially cut-n-paste my code into divs that are already styled as well as the structure to the overall page. All of my style declarations use entirely different names so that's good, but there are many styles that are causing problems.
I keep thinking there is a way to just add a class to the body and then over ride all other styles by the use of that class but I'm not sure about that. My tests haven't proved fruitful.
As there are three other style sheets that are called in the shell, I'm just trying to find the most painless and efficient way to integrate my content....like being able to insert everything into a iframe w/o using an iframe.
I have thought of duping all existing style sheets, renaming them and then just keeping the necessary styles from the cms but there will be a lot of extraneous css left over.
Any other ideas?
If I understand you correctly, you want to style the elements you are inserting without any clashes with the existing document stylesheets. Have you considered using a prefix so that for example '.container' would become '.my_container' e.t.c. This way to easily navigate the html and stylesheets for your elements you can just search for your prefix.
I have a large set (over 300) of C# ASP.NET pages *.aspx and controls *.ascx, which are littered with inline CSS styles. My task is to extract those style into a CSS file.
So I'm looking for a tool to simplify the task of manually extracting this inline styles and replacing them with class="" statements.
Now I know this is not the ideal solution of doing things, but any tool which could ease the task would be helpful.
No tool will write good CSS selectors for you, just like no tool can write good code for you. Yes, you can generate code from templates, but only for the most repetitive of coding tasks. CSS is more art than science, and as such "auto-generation" will not yield good results.
Writing good, clean, lean, maintainable CSS requires an intimate knowledge of the HTML markup, the style & layout that you are trying to achieve, and the skill of identifying patterns across the whole site, such as font, color, h1 headings, presentation of tabular data etc., which are re-used.
Even writing your own script will not produce good CSS. The best you could hope for is to extract all those inline styles, replace them with a unique id or class, and dump them all into a css file. I don't actually see a lot of benefit in that exercise. You actually end up with more code to maintain because of all the extra id's or classes that you will create.
You will not gain consistency of appearance throughout your site from the above exercise, unless you start to consolidate all those unique id's or classes into fewer, more re-used ones, and this is a task best done by hand, not automation anyway. Page load times may improve due to browser caching of the css stylesheet, but thats about all you gain.
Sorry if I've strayed a bit from your question, but your site sounds like it is crying out for you to re-write your CSS from scratch.
Check out CSS Zen Garden for inspiration on what CSS can do, and examples of beautiful CSS, and be inpired!
I would probably opt for using a scripting language with regular expressions. This seems like it would fit especially well with python's list capabilities - for each match to your regex, you can check the list to see if there is a corresponding entry, extract and assign the class from that result, and add each non-listed match to the list to continue building it up.
You can use this tool, it will look for inline style=... definitions replace them with class definitions and generate a style sheet. Hope this is helpful.
I have a messageboard and one of my users has written a greasemonkey script to stylize various elements within the page. He did a great job with it but in order to make his job easier, the first step in his script is to parse the current page and add several css classes to almost all html elements on the page. most of them aren't used to style the page at all, but instead to make it easier for him to query the couple elements per page that he will actually modify. for example class="thread_started_by_user_123 thread_with_456_posts thread_with_789_views thread_last_posted_in_by_user_12345" etc etc
is this a standard practice? are there any downsides to adding lots of unnecessary css classes, either in javascript, or on the server if i were to add them to served pages too.
This looks to be using classes to embed arbitrary metadata into elements, which is certainly not what the class attribute was designed for. Given that its effects begin and end with a greasemonkey script and are thus localized to the client, it seems a harmless enough hack, but not one I'd advise duplicating on the server side.
HTML unfortunately doesn't provide much in the way of alternatives when it comes to metadata other than sticking in invalid attributes, so there is a mechanism that does add semantic meaning to the "class" attribute within existing tags -- namely microformats. There's a lot of breathless buzzwordy hype around microformats, but overall they do revolve around a best practice for areas where going all-xml is out of the question.
In terms of semantics, yes there are downsides. If you have classes that aren't descriptive of what the element actually is and are there for styling purposes only, this can hurt you down the road should you decide to redesign and/or restructure.
for instance, BAD:
<div class="header red left-side">
GOOD:
<div class="header main current-event">
If there is no associated style with a class that's assigned to element, then I believe the browser will just ignore it. So it will not increase your page processing time a lot if that's what you are worried about.
However, if there are lots and lots of classes for each element, then you have to realize that you are using valuable bandwidth and increasing the time it takes to load the entire page that way. You can avoid that problem by externalizing the CSS so that the browser can cache it.
Are you using jquery to query the elements that you really want to modify? It might turn out that its more easy to pick those elements with jquery selectors which seem difficult or impossible with standard JavaScript and thus you can possibly avoid all these extra unnecessary classes.
Bottom line, there is no problem in using lots of classes if they are needed, and that's perfectly fine for production, but if you don't need them, like in your case, there has to be a better solution that you can possibly come up with.
Just for a data point, I took a look at GMail's HTML yesterday (their buttons are very nice) and it's full of that kind of thing.
Here's an example:
class="goog-imageless-button goog-inline-block goog-imageless-button-collapse-left goog-imageless-button-collapse-right"
Classes are not just for CSS, they're for the categorization of sections of markup. Applying styling based on that categorization is just one use. So if the classes are useful for other categorization purposes then that is fine, and perfectly good practice.