Are CSS selectors without properties of any effect? - css

I got a maintenance job and there is a huge CSS file, in which I found a lot of things like the following:
.xxxx {}
That is, a selector with absolutely nothing in it. I think they are useless, but there are so many of them I start to doubt myself. Am I right that they can be removed safely? Or they actually are doing something and I should keep them?

I'd say it's probably the worst design in history (or a stronger contender to the title...) but it could be used.
See below:
document.styleSheets[0].cssRules[0].style.setProperty('color', 'red');
.randomClass {}
<div class="randomClass">No styling?</div>
You can acces, process, and even modify stylesheets. Even if a selector is empty of styles, that can be modified using code.
So, it's probably very safe to remove, but if you want to be 100% certain, either leave it there, or go through all possible code branches.

Related

How do I refactor my CSS? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to Manage CSS Explosion
I intended to build my web site with consistent styles and a coherent CSS scheme. But styles have crept out of control as I fine-tune individual pages (especially the main search form).
I've already gone through the process one time of breaking down the styles and rebuilding almost from scratch, and now it looks like time to do that again. How can I be efficient about this? I'm looking for a methodology, not a software utility (though I'm open to suggestions there...unless they cost money...).
Added note: I'm using a CSS framework and it's difficult to keep padding and margin coordinated.
Added note 2: The initial responses to this post are about best practices for CSS. Let's assume I already tried to follow best practices (in fact, I did). Now it's the clean-up procedure I'm looking for.
Added note 3: As of 14 June, combining this response (which I just found) with my post below is possibly a comprehensive answer.
Closure notes:
I learned my question is too general, and for that reason I wish I hadn't posted it. (Maybe that's why it got a down-vote ... I'll never know without a comment to explain the reason.) On the other hand I got just what I needed, so I'm happy I did post it.
I'm surprised I didn't get an up-vote for my answer -- even with the priceless input by others, I think it stands up pretty well.
My acceptance is going to be based largely on the usability of the answer, from my point of view -- a point of view that is sadly unable to digest some of the more exciting and comprehensive responses.
Closed as an Exact Duplicate
I just tried posting this again (subject, body, tags) to see if SO would suggest the post "How to Manage CSS Explosion". Interestingly, it did not. I added the tag refactoring to that post.
Split your css into separate files.
Put in one file the CSS reset (if you use one)
Then create a global.css file where you will put global styles that
apply to many-all pages
Then create individual files for your individual pages
Then start styling your pages. Every time you find a style rule that is reusable on many pages make it a CSS class and put it in the global.css file. Avoid using css ID's. You will find that you more often reuse things or will reuse in the future. In this case you use of course CSS classes.
Eventually you will find out that in your global.css you will find mostly CSS classes rules and html tag rules.
In your individual page CSS files you will find specific styles for each page.
That should give you a good first level of organization in your CSS. You can try to keep this separation through the whole development process, and for releases merge the CSS files into one and minify it.
my 2p worth about css cleanup, from a a previous similar question:
Tips for cleaning and maintaining a big css file
hope that this may help you together with others' answers!
start branching the project (here I suppose that you are using a version control tool) - that will allow you to play independently with the code and tag any milestone you will reach.
format your CSS with a beautifier - it will increase readability and will help searching for specific declarations without missing any instances.
try to identify unused / redundant css and get rid of it.
you could try to make your selectors shorter (e.g. .main .foo .bar might be fine as .bar) - it will improve readability and increase the performance, but take this with a pinch of salt and be ready to go back if things start to break at every step you take.
try to eliminate, if possible, any !important - make the selector more specific if needed. A css reset could help with that if most of the !important statements were made to fix browser-specific issues, otherwise introducing a css reset now could potentially add more problems than solve them - this, if there is no css reset in your app at all.
break and regroup the css into different modules (and files if that helps) - Object Oriented CSS is a possible technique to keep things more maintainable, it works best if you start with it but it may also help you in refactoring. https://github.com/stubbornella/oocss/wiki is a valid one but there are alternatives that you can consider, like SMACSS.
After that , you may consider using a css preprocessor such as Less or Sass, allowing you to define variables and mixins (similar to functions), modularity and much more - this may end up being a very expensive task though, so evaluate carefully if this will bring you more benefits than pain.
test as much and as often as you can, consider unit tests to make sure that any changes you make don't break anything somewhere else.
Sometimes re-writing everything may end to be less time consuming than refactoring, so don't be afraid to leave things as they are if your assessment will show that refactoring will not bring enough benefits.
EDIT
Things change and evolve for good; with regards to OOCSS/SMACSS approach, I have been happily following for a while, Yandex's BEM methodology for CSS, I would like to add it as an additional recommendation to the above
The first thing I'll do is separate the CSS based on the purpose. Maybe first the general page layout (DIVs, boxes, ...), then the styling (fonts, H1/H2/.../Hn titles), then some more specialized CSS (CSS for tables, for forms, for specific components of the site).
Such a separation helps to organize the changes; if you have to change or add a font, you know you'll find it in the styling section.
If you have to change the page layout, there goes the same, and so on.
Things tend to get messy when you have "individual pages"; is their layout so different?
You probably have to abstract the common features of the pages (for example, a main content container box) as long as you can.
Then think about specializing more the layout (1-column, 2-column) and so on.
If you have a programmer background, just think about classes and inheritance, the concept - yes I know it's a totally different domain... - but the concept can be useful in designing your css.
Based on this current round of work, here is what I've got so far:
the Planning
Have a system for handling To-Do notations in your HTML and CSS. Many IDEs support this directly, or a global search function will do just fine. Besides tagging issues, you want to note priority and perhaps even functional area (but keep it simple, not a burden).
Don't start revising your code. Use your To-Do system to plan first.
Make a concise list of your overall goals.
Consider overall sylistic changes such as color or font scheme.
Review best practices for CSS. Identify areas where your approach is ineffective, or where a good approach can be applied more consistently. Examples:
Consolidate classes
Eliminate haphazard use of in-line styles
Remove styles that are unused or redundant or conflicting
Improve general consistency; apply a set of conventions
Improve units of measure
Use class and id names that reflect content rather than format
Decide how much of the browser market you want to support and how much to embrace or rely on the newest standards.
Decide if there are any new approaches you want to adopt. Examples:
Use of a reset style sheet to standardize browser presentation
Use of a CSS framework
Use of a specialized library, for example to help with forms
Dynamic CSS (I recently followed advice to use PHP to handle my CSS, so I could dynamically control my color scheme. But I returned to straight CSS, because I like the presentation of CSS code in my IDE and the hybrid method messed that up.)
Review your list of goals and decide which should be pursued now. Any large-scale change should be treated as separate, if possible. If your column layout is a mess, it's not the time to learn how CSS can elegantly replace your javascript. The same goes for best practices, stylistic changes, etc.
If you have your CSS files configured for speed (for example, compacted footprint or all CSS in a single file), change that. Break the code into a human-managable format. Later when you're finished, try benchmarking to see if the more legible version is also efficient enough for production use.
Submit your CSS to a validator. Note any violations you want to fix.
Find instances of in-line styles in your HTML (search for the style attribute). Note any that should be moved to a style sheet.
the Work
Follow your To Do manager. Make common-sense back-ups. As you go, test your work on several browsers.
If you are into regular expressions, be warned: regex is often not effective or safe for rewriting CSS. (Not as hazardous as for HTML, but still). Regex may be useful sending CSS changes into the HTML, but again be careful.
If you have a lot of tweaks to margins and padding, try globally resetting all of them to 0px (okay, use regex here). Then systematically build them back up. You can resolve a lot of confusions this way. Of course, don't include any library or framework style sheets in this process.
Again, submit your CSS to a validator.
I see people has already suggested using approaches like OOCSS etc., so I'm going to offer a different/additional line of thought. I believe that the problem lie deeper than within your CSS and the way you write it. I believe the reason your CSS gets out of hand is this quote from your question:
... as I fine-tune individual pages ...
That makes me think that the problem much lie within your design, rather than you CSS, so let me elaborate a little bit on that. In my opinion a great design is a design that doesn't have to be customized for each individual page - and there are several reasons for that. The main reason is, as you've mentioned yourself, your CSS get out of control. Small tweaks and fixes on individual elements, depending on where they are placed, often leads to a mess that is a pain to maintain and work with. There is also a usability-reason in play here. I believe a UI becomes easier to use if the user is familiar with the UI and recognize herself from page to page, without to much variation. Of course you could have some element that isn't present on each page, or that vary somewhat between pages, but I always strive to keep them at a minimum.
My suggestion is therefor that if you intend to rewrite your CSS, which is time-consuming and hard work anyway, then why not go over and re-evaluate your design at the same time. You will probably find that there are elements that you can modify so that they look the same. Make it a goal to get rid of as many UI-elements as possible, without compromising the design. When you've unified the design as much as possible, then it is time to refactor your CSS, and maybe even your markup?
At this point, it might be better to get rid of all your CSS and start fresh. If you continue on your old code, it is easy to get lazy and get stuck with some of your old less efficient code.
For the coding, I believe the other answers contain lots of good recommendations and best practices. I would personally vote for OOCSS, a new discovery for myself as well, but it has improved the way I structure my CSS a lot. So have a look at that! That will also help you think in terms of reusing elements and the CSS for them, which goes a long way for simplyfing your CSS.
This answer is in regard to the note;
"I'm using a CSS framework and it's difficult to keep padding and margin coordinated." only.
Using a css pre-processor will solve this problem.
Because css has no way to assign inheritance and therefore we have to repeat 'margin:10px' over and over.
with a pre-processor you just do
#margin {10px}
#padding {10px}
then
.mySelector{
margin: #margin;
padding: #padding;
}
For the broader question rethink/simplify your design as your css is directly proportional to the complexity of the design and there is not much you can do about that.
See also, http://www.stubbornella.org/content/2011/04/28/our-best-practices-are-killing-us/
This is more advice about making your css maintainable than the Q of how to manage the process.
I create a bunch of separate css files each narrowly tailored to a specific attribute (colors, fonts, margins, corners) or feature (nav, form). Then I use a compile phase to combine and minify these files into one or more files to be sent to the client. I do this during my built/test process, but it could be done dynamically by a CGI script.
Before adopting a pre-compiler, consider the often-overlooked multiple-selector syntax:
element,
otherlement
{
margin:10px;
}
In this example, whenever I want an element to have a 10px margin, I add it to the list. I separate different sets of attributes this way - I may list the same element 5 times in my css - associating it with 5 different sets of attributes.
Also don't overlook adding various classes to the body tag to create OO-like inheritance - say you have 3 main sections of your site - assign the body tag a class based on those sections. Likewise, if you have 1000 product pages, you can give the body tag a class like "product485" and then create styles that apply just to that page. For example:
h1 {
margin: 10px;
}
.product485 h1,
.product484 h1
{
margin: 5px;
}
.contact h1 {
margin: 15px;
}
This might all be in a file called "margins.css" which specifies only margins.

Should I avoid using !important in CSS?

Sometimes !important is useful, for example if I have defined common style for all links on the site (selector, say, a), but when I want to override some rules I have the following choices:
Use more specific (longer) selector
Use !important
Which way is better and may be there are some guidelines?
Use !important very, VERY sparingly -- it overrides just about everything, even inline styles, and messes in a less-than-obvious way with the "cascade" of style rules that gives CSS its name. It's easy to use badly, and tends to multiply, particularly when misused. You can easily end up with a element with !important rules that you want to override, at which point you often have to either refactor your styles, or use another !important rule and contribute to the problem.
And once it's spread and you're using it everywhere, you're back up in the same situation you'd be in without it (difficulty in specifying elements specifically enough to override other styles), but you also don't have !important anymore cause everything else is using it too.
When faced with a situation where !important looks appealing -- or worse, one where it's already in use and spreading -- prefer to refactor your CSS if you can. (Frankly, if you need !important outside of a user style sheet, it's usually because your selectors are already way too specific, and/or you're not taking advantage of the C in CSS.) You'd do better to define your basic styles as close as possible to the html or body elements, and when you want to override, use as little specificity as you can get away with. That way, you have plenty of room to make changes. Usually there's a reason you want to override a style, and those cases can quite often be boiled down to a class name, a particular section of the page (read: a particular parent element), etc.
(The only real exception that springs to mind is if the styles you're overriding are effectively out of your control. (If you use a framework that has very strong opinions on how your page should look, for example, you might find it annoyingly difficult to override anything. I've worked with applications that actually inserted their own inline styles, where nothing but an !important rule could override them.) If you don't have full access to the code, overriding and refactoring can easily be more trouble than they're worth. You can use !important to claw back some control, as long as you're aware of the consequences.)
What i can say is that you should try to avoid it as much as you can because it means that there are redundant code, and give an indication that the CSS and styles are not well structured.
But in some cases its a must to use it and no way to avoid.
So just do your best.
Avoid it when you can as this is what most advocate but at the same time it is important.
Have a look at:
The importance of !important in CSS

Should I make my CSS easier to read or optimise the speed

As I was working on a small website, I decided to use the PageSpeed extension to check if their was some improvement I could do to make the site load faster. However I was quite surprise when it told me that my use of CSS selector was "inefficient". I was always told that you should keep the usage of the class attribute in the HTML to a minimum, but if I understand correctly what PageSpeed tell me, it's much more efficient for the browser to match directly against a class name. It make sense to me, but it also mean that I need to put more CSS classes in my HTML. It make my .css file harder to read.
I usually tend to mark my CSS like this :
#mainContent p.productDescription em.priceTag { ... }
Which make it easy to read : I know this will affect the main content and that it affect something in a paragraph tag (so I wont start to put all sort of layout code in it) that describe a product and its something that need emphasis. However it seem I should rewrite it as
.priceTag { ... }
Which remove all context information about the style. And if I want to use differently formatted price tag (for example, one in a list on the sidebar and one in a paragraph), I need to use something like that
.paragraphPriceTag { ... }
.listPriceTag { ... }
Which really annoy me since I seem to duplicate the semantic of the HTML in my classes. And that mean I can't put common style in an unqualified
.priceTag { ... }
and thus I need to replicate the style in both CSS rule, making it harder to make change. (Altough for that I could use multiple class selector, but IE6 dont support them)
I believe making code harder to read for the sake of speed has never been really considered a very good practice . Except where it is critical, of course. This is why people use PHP/Ruby/C# etc. instead of C/assembly to code their site. It's easier to write and debug. So I was wondering if I should stick with few CSS classes and complex selector or if I should go the optimisation route and remove my fancy CSS selectors for the sake of speed?
Does PageSpeed make over the top recommandation? On most modern computer, will it even make a difference?
should I make my CSS easier to read or optimise the speed?
You should do both.
You should write your CSS so it is readable and if you want to collapse it, use a tool that automates that to generate the "production CSS".
So you should be working with nice readable blocks and the published file should be tiny.
In terms of the specific selectors
#mainContent p.productDescription em.priceTag { ... }
Only adds value if you have
p.productDescription em.priceTag { ... }
Or
em.priceTag { ... }
In other places that you don't want to affect - for example if you had a "#secondaryContent p.productDescription em.priceTag" that you didn't want to apply the style to.
So if you want to use
em.priceTag
And have the rule applied to all, you'll actually see no performance issue (the difference would be about the same as the file-size difference you save anyhow by having less chars in the rule).
HOWEVER... don't pollute your HTML with tons of class="" attributes just because you don't want to write a proper rule.
I personally have found that the complex selectors are more confusing long term, just be sure to give the classes appropriate names.
Long selectors are going to have a performance impact as it requires walking of the DOM each and every time to analyze the process. The way I see it there are times and places for it, but it is an exception, not the standard rule.
Define you priorities.
Readability
Efficiency
Speed
Nowadays, except on a real specific projet and complex page, you don't need to obfuscate your code to speed it up.
First think to maintainability.
By the way, using #id is a good practice both for readability and speed, since it doesn't need to walk through all the DOM to find it. Same apply for you.

What to do with empty CSS rules?

After some code review I removed unnecessary properties which resulted in empty rules.
So I have know something like this:
table.foo
{
}
table.foo td.bar
{
padding: 5px;
}
Now, what would be the best course of actions about this empty table rule? Remove it or leave it? Is there a requirement to have declaration of parent elements to be able to define child elements on them? It actually works without it just fine, but maybe there are some validation considerations? Any input is appreciated.
No, you do not need the empty rule.
Each rule stands on its own (that is, the selector for the rule provides the context), so you do not need an empty rule for table.foo in order to have a rule for table.foo td.bar.
Lava Flow is bad! Lava Flow is a programming anti-pattern which essentially means that people tend to leave code they aren't sure about needing just because they don't want to break things. However, your code works without it, so get rid of it!
I take it that your somewhat new to CSS, but you're clearly not new to programming, so I thought I would point out some useful frameworks for samples, consistent style, and a quick jump over the gotchas.
YUI's CSS Resources
http://developer.yahoo.com/yui/grids/
and Blueprint CSS
http://www.blueprintcss.org/
Also, YUI theater has some a couple good intro videos.
Hope that helps.
It's 100% unnecessary from a functional point of view. And the way you have things arranged it's also completely unnecessary from a style point of view.
Alternate CSS organizational schemes (indenting hierarchically, for instance) can make it worth it. If I have an element with children I'll often leave an empty selector lying around, at least until I'm done with the project and I'm optimizing, because it helps keep things organized and there's a very good chance I'm going to at least apply style to that element at a later time.
No, you really don't need to leave this. It will only let your project's CSS bigger. Unless if you are sick for organizing, you ought to let things like that.
Check out the Dust-Me Selectors Firefox extension - it finds all unused CSS selectors in a page, or even an entire site.
Just in case someone comes to this question with the same kind of misadventure that I ran into when I did, here is one case when an empty rule will actually make sure that the following rule is not ignored. I had an extra closing brace in the rule preceding the empty rule, and the empty rule helped resynchronize the parser.
Of course, the proper fix is to fix the syntax; and remove the empty rule.

CSS Selector Style

Simple question, and probably reflects my inexperience with CSS, but...
When creating a style sheet I like to explicitly specify the '*' wild card, so:
*.TitleText {
instead of just
.TitleText {
I find it reminds me that TitleText is applied to "any" tag, and can be overridden by a subsequent h1.TitleText. Maybe I just like this because for the longest time I didn't get that whole CSS selector concept properly and when I realized that the second (above) was just shorthand for the first, a lot of things "clicked".
Is what I do bad practice, good practice, or neither here nor there?
I don't know whether it's good or bad, but I've been doing CSS work as part of web app development for several years and I've never seen anyone use the * character.
While both are equivalent in terms of the style outcome, there are a couple other factors to keep in mind.
Using * increases the file size
If you do not use a CSS minifier (gets rid of unneeded data such as extra whitespace) that removes unneeded asterisks, using * every time a tag is not specified leads to quite a bit of extra characters in the file which will cause longer loading times (and more bandwidth usage). While I wouldn't go through a large file and remove asterisks already in place (unless you really have time to do so and love tedious tasks that could cause a bug you won't discover for years), I would suggest not including unneeded asterisks when writing new styles and removing unneeded asterisks when editing old styles.
Using * can lead to confusion
Using * when it's unneeded can lead to confusion, especially when someone new is working on the project and has not dealt with * being present when it's not needed (which is quite common).
Example
/**
* This matches an element with the class `alert` within
* any element within an `article` element
*/
article * .alert { /* ... */ }
vs
/**
* This matches an element with the class `alert` within
* an `article` element
*/
article *.alert { /* ... */ }
If there is 100% consistency in a project (and the style is known by all individuals working on the project), then the first example would never happen (it would be article * *.alert instead). However, this is an ideal situation and will more than likely fall apart after a few generations of developers (people love to use their own style instead). So, even if you have a consistent style, a new hire may come in and write in their own style for a short time, or read the current style incorrectly and produce code that doesn't match the selectors (or vice-versa). Therefore, I'd suggest sticking to the standard that I have seen the most (read: exclusively) in projects and websites:
Do not use the asterisk if it's not required.
A quick look at the source of some well known websites (e.g., Facebook, Google, Yahoo, etc) will show that they don't use asterisks unless they have to (even in their non-minified styles). You can also take a look at some open source projects on GitHub.
Conclusion
The asterisk should only be used if it is absolutely required (e.g., body * p to match paragraphs that have a parent other than body). Not only is this the unwritten standard (and less likely to cause confusion), but it also decreases the file size of style sheets, which increases the loading speed of the website.
Personally, I tend to only use the * when applying a rule to all tags. It is redundant in the case of *.class{}, but useful in the case of .class *{}.
I have read in a few places, but not verified, that the * selector can impact performance. It's not something I use unless I need to, as I generally prefer to be a bit more explicit, but that's just a personal preference.
It's neither good or bad, but it is (entirely) redundant.
EDIT: Actually, methinks it bad, 'cos it's potentially confusing (as in to humans, not parsers).
According to the CSS specification:
5.3 Universal selector
The universal selector, written "*",
matches the name of any element type.
It matches any single element in the
document tree.
If the universal selector is not the
only component of a simple selector,
the "*" may be omitted. For example:
*[lang=fr] and [lang=fr] are equivalent.
*.warning and .warning are equivalent.
*#myid and #myid are equivalent.
Therefore, .TitleText and *.TitleText are equivalent. It is highly unlikely that any implementation would have a performance consideration for *.xxx which is not there for .xxx.
This then boils down to a question of style. And since the considerations of style raised by the other answers seem to be to be largely moot, I believe I will go ahead and continue explicitly specifying the *.
I don't think it matters, but none of the examples I ever saw when I was learning used that wild card format, so I learned to do without the asterisk.
Also, none of the tools that generate CSS do it that way, so by using the asterisk, you risk an automated tool wiping out your format if you ever choose to put your CSS into such a tool.
Just for consistency with most other web developers, I'd probably recommend doing away with the asterisk so you don't have to deal with another developer asking why you've put an asterisk there.
I think the * is implicit, so they do the same thing.
I am not sure, but it might cause some problems if you do it like this:
span.style { color: red; }
*.style { color: blue; }
The * style will probably override the span style. I could be wrong though since span.style is a more specific selector.
I think it is pretty funny you do that, even though I totally get why! You're using DOS prompt/shell syntax with your CSS. In the end you might have been confusing yourself further thinking about it that way, since in a Shell you're looking at the file extension but in CSS it is actually mapping to a class.
So what I mean is, it works for class selectors, but kind of falls over for ID selectors. For example:
span#id { ... }
*#id { ... }
...and it no longer looks like Shell syntax. :) Personally I wouldn't do it the way you're doing it, because it might be confusing, but I don't think you're breaking anything.
That would be redundant, assuming * means 'every possible thing in the world' not having a * would also mean the same. I normally use *{margin:0; padding:0} in undo.css to reset the margins and paddings , but never as a pseudo selector.
I have never seen anyone use the wildcard like that, and I suspect it will be picked up in preference to just specifying the class. Other people modifying the styles maybe forced to keep using that syntax. That is if they figure why their classes are not working.
*.class will overwrite span.class even if span.class is more important.
I see no practical use for *.class, overwrites should be done with !important statement and only sparsely.
The only reason i use * is to remove all padding and margins, i actually always do this its the first css statement i write down always :).
There are also quite a few css hacks based on "* html" not working in IE6 and lower.
I'd flag it as bad practice.
In terms of the CSS specs, your two examples have identical meaning. However, there are potential issues with it in practice. The biggest, that I can see, is that some browsers may mistreat * in terms of rule weighting and so potentially throw off precedence (though I do not know of any, off the top of my head, that do this — it just wouldn't surprise me). It is also widely held, though I can't quote chapter-and-verse at you, that class selectors should always include a specific tag name for performance reasons. It is apparently faster to apply a class selector with a tag name (span.foo) than without and faster to apply an ID selector without a tag name (#bar) than with.
EDIT: This is pointing out that there could well be a performance issue. Some people seemed to think I was some sort on way out there rant...
While I don't know for certain, I'd like to give a word of warning! Consider the following identifier:
div#foo a.bar {}
I hear that jQuery for example, which utilizes css, would in the above example traverse the DOM looking for divs first, then check to see if they have an id of #foo, then for an A tag before finally seeing if it's classed .bar.
My concern with the * is that the browser may traverse the DOM looking for ALL tags and then look for .bar, rather than inherently just looking for the attribute of 'bar' - that's two sweeps of the DOM rather than just the one. Might be an extremely minimal difference, but if your syntax hits the airwaves, that's a few more solar panels we need to install.

Resources