What is diffrence between CSS frameworks and preprocessors? - css

I know Bootstrap and Foundation are CSS frameworks, but I'm not sure whether LESS and SASS are CSS frameworks or preprocessors.
What is the difference between CSS frameworks and preprocessors?

From http://lesscss.org/:
Less is a CSS pre-processor, meaning that it extends the CSS language,
adding features that allow variables, mixins, functions and many other
techniques that allow you to make CSS that is more maintainable,
themable and extendable.
From http://sass-lang.com/documentation/file.SASS_REFERENCE.html
Sass is an extension of CSS that adds power and elegance to the basic
language. It allows you to use variables, nested rules, mixins, inline
imports, and more, all with a fully CSS-compatible syntax. Sass helps
keep large stylesheets well-organized, and get small stylesheets up
and running quickly, particularly with the help of the Compass style
library.
Basically both are css pre-processors, as in they allow you to write style information that later compiles to css.
Frameworks, like bootstrap, on the other hand are more like pre-made style sheets that can be used to save development time. Rather than writing out custom sheets with similar styles over and over again, you can make use of prefabricated sheets. They usually have things like resets, basic layouts, and/or grid systems built in.
There are also some frameworks written in, and designed to be used with a pre-proccessor like Less Framework 4
If you're relatively new to this stuff, I would recommend starting with plain old css. Pre-processors can be helpful, but the learning curve is a bit steeper.

As said above, LESS and SASS allow CSS to follow the DRY(Don't Repeat Yourself) principles of coding. For example if you had a CSS file where you wanted 12 items let's say; h1, h2, h3, h4, p, a, etc all to have the same color of text(let's say a salmon color), what these preprocessors allow you to do is create a variable(let's say myColor), that you can then pass into the color attribute of each of these items.
This may not sound exciting, but where it really shines is when you want to say redesign the site or alter that color to say a 'sky blue' instead of now skimming through those 3000 lines of code to find those different items (h1, h2, ... , a, etc as listed above) you'd only need to change the myColor variable from the hex/rgb/rgba color code to the one for sky blue. Which in turn would change that value for each of those items.
So essentially you need to change 1 value that's easily found, as opposed to many, which may require a lot of sifting through code.
To note though, LESS and SASS cannot be read by a standard Internet browser, instead you must use a program that compiles your LESS/SASS code into standard CSS (these programs are easy to find and most programs such as Sublime, Brackets, Atom, etc have the functionality built in or allow a package to be downloaded that does it.)
Then when you need to edit your code, you change the LESS/SASS file and recompile again.
That's just the tip of what LESS/SASS can do, but it gives you an idea hopefully of their use. Programmers are lazy, copy and pasting isn't a good option generally, as you violate the DRY principle. So this is a happy medium explained hopefully in laymans terms.

I would have to believe I can accomplish the same results as pre-processors using jQuery(the most popular ui/ux framework).
However, depending on how many people are working on one project it may a case of teams learned in SASS or LESS scripts and may not know jQuery syntax as well. They are only focused on CSS effects, which could be a plus.
If I .addClass() to multiple DOM elements with jQuery... it may be even more efficient than having a preprocessor duplicate desired code all over a css file.

Related

Copying CSS classes

Lets say that youre using Twitter Boostrap and you have their generic boostrap.css and other boostrap associated css files, and you want your own classes to have identical attributes to some of the given boostrap classes. To my understanding, you would not want to directly modify the css bootstrap files, but you would want to extend them by creating a custom.css file.
So without touching the boostrap files. How would I replicate a boostrap class for my own class? Would the only way be to copy and paste from the boostrap.css file. Or is there a way to do
.myownclass {
-- some command to replicate class 'alert alert-error' without repeating the CSS that has already been written
}
You could use a css preprocessor. Other ways already cited by other users are fine but using a css preprocessor is the best way.
Bootstrap is built using LESS, so you can use LESS. Take a look at here: http://bootstrap.lesscss.ru/less.html.
Also SASS can be used. According to me SASS is better. You find a tutorial here: http://www.1stwebdesigner.com/css/build-website-using-twitter-bootstrap-sass-1/
What are CSS preprocessors?
A browser can only understand CSS, as the styling technique for any DOM element being rendered. CSS, as a language has its own feature set, which at times might not be enough to create a clean and reusable chunk of rules. Eg. Not being able to reuse a collection of rules in multiple selectors, unavailability of variables which may lead to ambiguous pieces of data across the stylesheet. To overcome most of these limitations, the concept of a preprocessor was born – offering an advanced way of writing CSS, which extends the basic functionalities. This advanced code is later compiled as normal CSS code using respective compilers (which depends on what preprocessor you are using), which the browser will understand.
Should you use preprocessors?
The decision of adopting preprocessors for your next project, in my opinion, should be made after much analysis and solely depending on your expertise level and most importantly the project requirement and workflow of the team as a whole. Here are some tips that might help you come to a decision:
Not for beginners: If you are a beginner and starting to explore the fantastic world of CSS, I would suggest you get your hands dirty with normal CSS before moving into a framework or preprocessor of any sorts. It’s really important to understand and be able to use the core concepts of any language that you work with, and that’s true for CSS as much as any other programming language.
Are you a team of front end developers? As a team of front end developers, adopting preprocessors will be a great move. But only if somebody on the team really knows how to handle huge CSS files and structure them accordingly. By making use of the powerful features offered by the language, it is important to first structure the whole CSS into reusable chunks and define a strategy for CSS organization. Eg. Are you going with multiple CSS files for typography, forms, layout etc. Are you going for theme-able UI, where you might need to use variables extensively, etc.
Are you willing to cross the barrier? Adopting preprocessors means you are going to be implementing more programming concepts into your CSS coding approach. There will be a lot of concepts that are native to any basic programming language, which you might want to learn and implement, by using a preprocessor. This means, you will definitely need to brush-up your programming skills and might forever change the way you see a CSS code. If you are willing to cross this barrier, and feel ready to embrace the change confidently, this is for you.
In CSS this is not possible. The only way to do it, is to chain the classes in your html tags.
<div class="alert alert-error myownclass"></div>
If you are using less you can do it like this:
.myownclass {
.alert
.alert-error;
}
This will copy the settings from one class to another. The result will be the same as if you copy the contents of the class directly.
If you are using Sass you can do it without copying the class contents. Just reference the classes as shown below. This will not copy the contents, instead it will reference your custom class at the right position in your css code.
.myownclass {
#extend .alert;
#extend .alert-error;
}
Ref: Sass #extend
You would have to use LESS to avoid copy/paste:
.myClass {
.bootstrapClass;
}
Or you could use any of the other CSS preprocessors TBS has been ported to (Sass has one, not sure on the others).
You could give the element two classes - the original Bootstrap class, and then one of your own making. Then you would target it like this:
HTML
<h1 class="original_class myownclass">Hello</h1>
CSS
.original_class.myownclass {
// css code
}
Here's a little jsfiddle illustrating the concept: http://jsfiddle.net/ApEpr/
This does not require the use of a CSS preprocessor - it's just regular old CSS.

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.

Structured way to organize CSS code

When building a relatively large website, the CSS structure ought to be properly scoped and organized right from the begininning. If no CSS framework is used then everything can be lumped together into a massive stylesheet, but this will very quickly get out of order and can become a huge maintenance liability.
For the past few years, I've broken my stylesheets into various files including: base.css, layout.css, fonts.css, elements.css, but very easily the style definitions can jump between files and this approach needs to be more strict. I haven't used a framework since I'm not a fan of preset columns and pre-defined elements in my CSS code.
What approaches, patterns or tips can you guys suggest for keeping things organized? What kinds of naming conventions, reusability practices and patterns are useful? Is this something that a framework should be used for?
I used to love LESS, but now I'm a big fan of Stylus because I think it makes even cleaner code than LESS/SASS/CSS -- no semicolons, colons, or brackets.
Because Stylus (and LESS and SASS) allow you to define variables and templates and functions, I have the following files, which should be in this order:
reset - A Stylus version of Eric Meyer's CSS reset
variables - Variables like colors, fonts, etc.
templates - Templates like border-radius, transitions, and clearfix
Stylings for each page (homepage, app, terms of service, etc)
These are all concatenated and compiled to CSS using a simple build script.
You can see what these look like; I made a GitHub repo for this stuff.
For writing consistent and manageable stylesheets CSS LESS Framework is very beneficial.
LESS provides the following mechanisms: variables, nesting, mixins, operators and functions for writing CSS codes dynamically and can run on the client-side (Internet Explorer 6+, WebKit, Firefox) and server-side, with Node.js or Rhino.
http://lesscss.org/
Regarding Stylus — lack of semicolons, colons, and brackets makes your code less readable IMO, rather than moreso.

Tools and techniques for refactoring CSS

I need to do this more generally, but a fine current example is my two menus. I have two menu classes, horizontal-menu and vertical-menu, and two sets of rules for elements like ul, li, and a under these classes. Many of these rules have things in common, like the color value for a elements. I would like to refactor the common rules and values into a 'super-class' called menu, and the have only override values in my horizontal-menu and vertical-menu classes. Is there a tool (besides the tool asking this question) that can help me with this?
The best tool for this kind of problem is Compass, a framework for defining rules which are then compiled into css for use in production. It allows you to define variables in much the same way as an imperative language.
It also has other helpful concepts such as mixins which allow the definition of a set of css properties which would be regularly used together, such that you can include that block of properties in multiple standard CSS rules. The power being that you can then edit that mixin in one place, changing the properties and having that change propagate to any CSS rule in which the mixin has been used.
I discovered Compass, and learnt how it should be used thanks, to a screencast by Chris Coyier at CSS Tricks
The only problem in this case (and most cases in fact) is that you really have to start from scratch with Compass, or find a way of integrating its work-flow into your existing one.
You may want to give csscss a shot. I wrote it in order to have an idea of how much I'm repeating myself in my own stylesheets. I'm obviously biased, but a number of people have found it helpful too. SASS, LESS, and Compass support are baked in.
Another great tool is helium which is a javascript tool that runs in the browser and lets you know of any unused rules.

X is to CSS what GWT is to Javascript; what is X?

Is there a structured language for declaring styles in a sensible way, which can then be rendered into browser specific css files, similar to what GWT does to Javascript?
It would ideally be a language that supports variables, deals with browser quirks and differences (e.g. filter:alpha vs opacity), provides an intuitive syntax for common tasks such as centering, and has a way to express fallbacks for less capable browsers.
Sass, as in Haml and Sass has some of what you're looking for.
It has variables, math, and other goodies.
The official version is Ruby based, but there are versions for other languages like PHP and Python.
It might not do EVERTHING you mentioned, but it's worth checking out.
GWT's ability to generate code on the fly and it's powerful "deferred binding" capability could definately be applied to stylesheets and allow for build-time optimization of CSS.
Right now, the "GWT way", according to styles is to include all the styles you'll need and use apply them by making use of "dependent style names". But this definitely leads to lost of useless CSS being included where it's not needed.
I know there is at least one attempt to optimize CSS at build time. This would involve combining multiple seperate stylesheets into one, and removing all non-essential whitespace (minifying). I think this might also allow you to make use of deffrred binding to essentially "optimize out" CSS from where it's not needed (ex: browser specific styles).
StyleInjector
To answer my own question (again): Less seems like one of the most interesting projects so far. CSS extension supporting variables, mixins (complex variables), nested rules, and simple arithmetic.
you might want to try HSS.
Thanks for your comments! Sass and HSS seem very similar in scope: simple and block variables, nested blocks, single line comments. HSS has the advantage of being a superset of CSS.
StyleInjector looks more ambitious and interesting. By leveraging GWT's deferred binding capabilities and introducing CSS syntax extensions like conditionals, this approach should make it easy to define not only browser specific but also locale specific styles. Also being able to reference other GWT resources directly, and automatically minimizing styles by removing and merging selectors is pretty cool. I'll definitely follow this project closely.

Resources