CSS Frameworks & "Semantic Naming" - css

I've looked at two CSS frameworks that could save me a lot of time (Blueprint, 960gs) but have questions on how to use them and comply with web standards. For example, Blueprint has things like:
<div class="span-24 last">
and 960gs like: <div class="grid_6 prefix_3 suffix_3">
This doesn't personally bother me, but I've seen mention that using these non-standard names for classes is not advised and goes against web standards. As more of a back-end developer, I'm not up on the latest Web Standards, accessibility, etc., but I'd like to at least stay somewhat compliant. Would simply adding meaningful ids work? Like: <div class="grid_12" id="menu"> Is there a best practice when using CSS frameworks like these?
Note: I also like nicholaides's suggestion of using Compass/Sass!

I think you're confusing a style argument with a standards argument. There are people who argue that when creating a class you should call it 'headline' and not 'blue' - simply because if the headline needs to become green, you have to change the class definition AND the HTML rather than just redefining the 'headline' class. That's a personal preference, it's good style, but not related to any standards.
There are no 'standard' names for classes, you can call them anything you want, so I wouldn't worry about naming classes any particular way from a technical standards perspective.
Additionally, since the classes that a CSS Framework create aren't meant to be edited by humans, but only used in the context of the framework, their lack of semantic meaning is irrelevant outside the framework.

I don't see how
<div class="span-24 last">
and
<div class="grid_6 prefix_3 suffix_3">
fails to comply with web standards. This is simply multiple classes assigned to a single element.

In the long run, your saved time will be lost. You may find yourself forever flipping between your css and your html, trying to remember what "grid_6" is. Descriptive class names will help a lot.

Check out Compass.
It uses Sass (which compiles to CSS) and that uses features from a number of popular CSS frameworks. (It's not as scary/bizarre as it sounds. Sass is a great replacement for CSS even without the CSS framework support.)
Instead of doing
<ul class="column_6">...</ul>
You do:
ul.naviation
color: #fff
+column(6)
which compiles to
ul.navigation {
color: #fff;
/* all the rules for the 6th column a placed here */
}
You can take advantage of CSS frameworks while keeping your markup clean and semantic.

Don't use CSS Framework
because your website will not use everything the framework offers.
It is just good to take it as a reference and write your own CSS.
It will be easier to maintain, and your css file will be smaller.
Only part I would use is..the reset.css file from 960.gs
The reset css file is widely used to remove all the default white spacing with DOM elements.

You could try naming elements with id of upcoming html5 name specifications:
hml5 sheet which is pretty wide specified for use everywhere. If you stick to this naming conventions you should mediately remember purpose of design element. If more precision is needed try to use some human readable format that you will understand - your writing comfort is key to quality code.
If you are interested more in that topic read full article on smashing magazine "html5 and the future of the web" ( google it: new user link limit :/)

Related

What is the best Approach for CSS framework of an Enterprise Cloud application?

There are several ways to style the elements in each page, in Enterprise applications usually the CSS Framework size increased about 1 MB, and when your users are using slow internet connection, you should decrease css framework size.
we can create new CSS for our element like .Blah and value it in css framework and do this for each element which cause increase size of css framework, but a cleaner page
<div id="blah" class="blah"></div>
we can also use our css framework utilities in each view to format each element to keep size of css framework, but a non-clean page
<div id="blah" class="margin10 padding20 bg-color-red fg-color-white text-bold else"></div>
which of above approach is the best approach for an Enterprise application, while you ensure that a majority of your users are using slow internet connection
File sizes
My first point would be that when dealing with an enterprise level application the actual total quantity of css when measured in megabytes is slightly less important, even for slow internet connections. It's important that the pages you load into an empty cache of a potential conversion that just clicked your pay per click ad for the first time are as tight as you can possibly make them, but for an app that a user is paying for and is intending to invest their time and effort, priming a cache every release, even with a megabyte of css is less of a problem. You could load it all last on the login page so it's all sorted while they put their credentials in.
Furthermore, you'll have the time to investigate some other techniques, such as loading critical 'above the fold' css in it's own, optimised file first; and splitting the css files up so that the common stuff is loaded on the first page view but any page specific stuff is loaded per page, as it's visited (for the record, this can be very good for the aforementioned PPC targets).
CCS Tricks goes into more detail here and here.
Complexity
One of the bigger considerations of enterprise cloud applications is the maintainability of the css. You're probably going to have a team of developers and a complex user interface. These things can quickly turn into a maintenance nightmare if the wrong decisions are made concerning the approach to css.
It's all very well if you users can load a page in 0.1s less, but if it takes you 30mins more to make every simple css edit then you're in trouble.
My recommendation
You want a combination of both. You should strive for semantic, context free css selectors in order to hit maximum re-usability (and low file size) and maximum maintainability. This allows for effective file size management and effective, scalable development.
For example:
.blue-box
.header-login-box
.contact-form-submit .green-button
bad: not semantic, or too context specific. I'm assuming that .blah pretty much falls into this category, judging by the phrase 'do this for each element'.
.login-box
better: easier to re-use, semantic, but still too contextual
.box--highlighted
.button
.button--standout
even better: really re-usable because of complete decoupling from page context, but still clearly semantic, making it easier to maintain.
With the final examples you break your app UI designs down into modules which are defined and re-used wherever they are needed. It's conceivable that you may use more than one per HTML element, but you won't have ten.
It's also OK to use utility classes, such as .pull-left in fact, Harry Roberts at CSS Wizardry, a successful consultant whose done this stuff in the wild for real clients recommends it.
Three further avenues of investigation
There are currently three organisational / naming strategies for scalable css architecture that try to tackle the problem, you might want to look at them in more detail:
BEM: docs introductory article
OOCSS: docs introductory article
SMACSS: docs and introduction
All three will help maximise re-usability and minimise file sizes while giving you rules to follow to keep things tight and help with new members of the team.
I think the correct answer is: "Find a happy and maintainable In-Betweener".
The modular approach
Namespacing your CSS classes by modules can be very valuable. You can just drop that parent CSS to an element, have all children DOM elements respecting your CSS structure and you can end having a very modular and powerful CSS framework. But, As you sad, it can start bloating you CSS files as namespaces CSS classes would be applied to all child elements.
The "use-css-properties-as-css-classes" approach
You might get tempted to use this approach as it gives you great flexibility for your elements in the page. The problem is re-usability. If you define that a specific component should always have its title set to "bold". Do you expect to apply the class "text-bold" every time you need to use this component? This can become a maintainability nightmare and I'd use it for exceptions only.0
The modular-with-variations approach
My favorite one: Break down your app in common reusable UI components.
Also think about how these components might vary: sizing, colors or optional child elements. Then apply CSS properties as classes for the exceptions.
Your CSS code would then live under the following structure:
Majority of CSS work encapsulated by modules/ UI components (CSS namespacing)
Some or several CSS variations for your UI components
Property-like CSS classes for exceptions and page-specific variations
Tips
Download source codes from existing CSS frameworks such as Twitter Bootstrap and study how they reuse CSS across different UI components.
Consider using pre-compiled CSS such as LESS or SASS as you can make use of functions and variables.
Use short css names for component names (so they don't bloat your final CSS file
group, minify and gzip your css files.
Examples
CSS classes
/* Panel Component */
.panel {
width: 100%;
}
.panel-content {
padding: 10px 20px;
}
/* Panel variations*/
.panel-success {
background-color: #3F3;
}
.panel-with-icon .panel-content {
padding-left: 50px;
}
/* Exceptions (Helpers) */
.pull-right {
float: right;
}
.margin-top-20 {
margin-top: 20px;
}
HTML usage
<div class="panel">
<div class="panel-content">
Simple panel
</div>
</div>
<div class="panel panel-with-icon">
<div class="icon">
my great icon
</div>
<div class="panel-content">
Panel with icon
</div>
</div>
<div class="panel panel-success margin-top-20">
<div class="panel-content">
My successful panel with page specific tweaks
</div>
</div>
I hope it helps you.
I always go with the 2nd approach, because:
1.It's easier to maintain, you never know when you'll edit your pages. So for example if you give your elements a class of my-color and you wanted to change that after a while, all you need to do is to go to your css file and change my-color color, Imagine the time you save, and of course time means money.
2.You don't repeat your style, and that'll lead to less .css file size, and thus a a faster website.
3.You can make your .css stucture once, and then reuse it in every project. You'll have to change the style only. For example, you can have .my-color in every project with different style. Instead of making it from scratch each time.
The drawback is you'll have a larger .html pages, but usually browsers cashe your page and
in many cases the amount of loss in markup performance will be greatly surpassed by the amount of gain in stylesheet performance
Quoted from http://www.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/
This approach is called OOCSS = Object Oriented Cascade Style Sheet, it isn't considered a best practice yet, but it's evolving.
You can read more here
http://oocss.org/
http://www.smashingmagazine.com/2011/12/12/an-introduction-to-object-oriented-css-oocss/

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.

CSS Best practices when starting a new project

I wanted to know what's the best approach to take on, when starting work on a CSS of a big project? Because I see on most big projects (like wordpress) that they bunch all the classes sharing same properties together, however, how can you know before hand that they'll be matched, or is that the post-programming micro-work?
Anyway, Just wanted to know the best practises for grouping classes, ids and such, and what's the industry standard approach on this manner.
CSS Frameworks
For big projects, you'll likely want extra functionality on top of 'regular' css, like nesting, inheritance and mixins. Either one of these should get the job done:
SASS
xCSS
LESS
OOCSS
Performance optimization
Also, you'll want to do automatic performance optimization (concatenation, minification, and compression of source files), so take a look at:
Minify
or whatever suits your development platform.
Naming
Many large sites use some kind of prefix on class names to separate style classes from script classes. E.g.:
<div class="navigation dynHomepageNav">(...)</div>
Where the dyn* class is used as a selector in scripts, while the navigation class is used for styling. The benefit is you can have coders refactoring scripts without touching the design, and designers changing the templates without worrying about breaking functionality.
However, with modern Javascript frameworks and HTML5 you can do better; use semantic naming for IDs and classes, apply style using those IDs and classes, and use data-* attributes for all script hooks instead. Example:
<section class="navigation" data-hook="homepageNav">(...)</div>
Which you will style using the class identifier:
.navigation {
border: 1px dotted #9c9;
padding: 12px;
}
And script using the data hook (using James Padolsey's data selector attribute for jQuery):
$('section:data(hook="homepageNav")').fadeIn();
It may not be as concise or look as familiar as the good old use-semantic-classes-for-everything method, but it will create a neat separation of style and behavioral properties, which you'll appreciate once you have 50.000 lines of HTML and you need to revamp the design.

Best Practices - CSS Theming

Quite often when I design a website for a customer, I design his website with one (or multiple) CSS files that makes up the entire presentation layer. The thing is, usually, the customer's needs change drastically in terms of "website theming". He may end up asking to change from a blue/green color-based theme to a red/orange based one according to his tastes. The thing is, my file contains all the information including:
the positioning of elements
the background images of containers
the font size, color
What are the best practices for "decoupling" a CSS file to make it "theme" aware, while maintaining all its information on positioning?
My list of possible practices are as follow:
Use a default CSS file containing generic information and positioning, use child CSS files that implement only the background images, font-sizes and colors
Name your first CSS file (say here the blue/green one will be named "sky"). Implement another theme based on sky, overriding any CSS attributes needed to change the theme and name it (red/orange would be "crimson" for example).
EDIT: according to the great answers provided below, I updated the list of other possible solutions adding up to my list:
Use SASS, (best authored with Compass #see Andrew Vit) specifically their "Mixins" feature. It takes CSS and introduces a very DRY programmatic approach. You can override existing classes with it. -treefrog
Use an OOCSS approach. -Andrew Vit
A technique called independent blocks (article in Russian) that mimics a sort of namespacing using class prefix to seperate specific blocks. -angryobject
Three based stylesheets. Separating typography, position, and the reset stylesheet provided by Eric Meyer. -David Thomas
Use already standardized approaches used by known organisations such as the Dojo library, jQuery UI, etc.
-S .Jones
Which would be better in which possible case? Are there any other easily maintainable and flexible ways?
Best answer to date: Using SASS to make very flexible stylesheets. Of course this implies the slight learning curve, but according to a few reviews, SASS seems to be the next approach for dynamic stylesheets (along with HAML).
You should look into SASS, specifically their "Mixins" feature. It takes CSS and introduces a very DRY programmatic approach. You can override existing classes with it, making it perfect for what I think you're trying to do.
Link
Consider the approach suggested by OOCSS. The general idea is to separate the style concerns of your classes into more granular units, so that you end up using more classes in your markup instead of hanging all of your styling on too few classes with overlapping concerns.
This can be combined with some of the other suggestions. (I highly recommend authoring SASS with Compass!)
In situations where a theme is required I, personally, tend to use three base-stylesheets:
A reset stylesheet (typically Eric Meyer's)
A stylesheet for positioning of elements (margins, paddings, floats, etc)
Typography and colours
There is an awful lot of repetition in this approach, though, so #treefrog's answer may well be a better approach. The one saving grace I can offer for my approach, which is why it works well for me, is that it's easy to know where to go to change the title font from Arial to Times New Roman (or whatever), and where to find the background-colours for the page. Typically these are stored in a Wordpress-like arrangement:
http://www.example.com/css/reset.css
http://www.example.com/css/themeName/typography.css
http://www.example.com/css/themeName/layout.css
I know about a techniques based on using so-called independent blocks. A block here is a part of the page that can be described by its own layout and its own styles. There are some principles of that techniques like using only class attribute, not id; each block has a prefix; no styles outside blocks or minimum global styles. But those are optional more or less. Suppose you have a block:
<div class="b-my-block">
<span>some more content</span>
</div>
And a style for that block:
.b-my-block{
width:100%;
height:300px;
}
.b-my-block span{
background:red;
}
'b' here is the prefix for the block. You can have different prefixes for you needs. You may want to use prefix 'g' for some global classes that can be applied to and modify any other elements.
Then, if you want to extend this block or change it somehow, you can create a modification of this block with a class 'b-my-block_blue' for example:
<div class="b-my-block b-my-block_blue">
<span>some more content</span>
</div>
and a piece of css:
.b-my-block_blue span{
background:blue;
}
This a very very rude example. And i'm not sure if i was explanatory enough. But i'm trying to use this technique in my current project and it feels pretty good so far. There is an article on this in russian. Maybe someone could translate it in english, if it has some interest for the people here.
Good Question. +1
I think for simpler layouts, where you can get away with theme changes based only on colors defined within CSS, then it makes sense to separate your CSS files into a core 'structural' file and several themed versions.
For more complicated themes, where images are imported as key parts of the layout or theme, it's better to completely nest your resources under a theme. You can see examples of this by exploring the directory structures of Javascript packages like Dojo that allow you switch between multiple themes. If you look through "Tundra" or "Soria" directory structures within the Dijit library, you'll see which 'best practices' they employed in dividing up their CSS files.

What's so bad about in-line CSS?

When I see website starter code and examples, the CSS is always in a separate file, named something like "main.css", "default.css", or "Site.css". However, when I'm coding up a page, I'm often tempted to throw the CSS in-line with a DOM element, such as by setting "float: right" on an image. I get the feeling that this is "bad coding", since it's so rarely done in examples.
I understand that if the style will be applied to multiple objects, it's wise to follow "Don't Repeat Yourself" (DRY) and assign it to a CSS class to be referenced by each element. However, if I won't be repeating the CSS on another element, why not in-line the CSS as I write the HTML?
The question: Is using in-line CSS considered bad, even if it will only be used on that element? If so, why?
Example (is this bad?):
<img src="myimage.gif" style="float:right" />
Having to change 100 lines of code when you want to make the site look different. That may not apply in your example, but if you're using inline css for things like
<div style ="font-size:larger; text-align:center; font-weight:bold">
on each page to denote a page header, it would be a lot easier to maintain as
<div class="pageheader">
if the pageheader is defined in a single stylesheet so that if you want to change how a page header looks across the entire site, you change the css in one place.
However, I'll be a heretic and say that in your example, I see no problem. You're targeting the behavior of a single image, which probably has to look right on a single page, so putting the actual css in a stylesheet would probably be overkill.
The advantage for having a different css file are
Easy to maintain your html page
Change to the Look and feel will be easy and you can have support for many themes on your pages.
Your css file will be cached on the browser side. So you will contribute a little on internet traffic by not loading some kbs of data every time a the page is refreshed or user navigates your site.
The html5 approach to fast css prototyping
or: <style> tags are no longer just for the head any more!
Hacking CSS
Let's say you're debugging, and want to modify your page-css, make a certain section only look better. Instead of creating your styles inline the quick and dirty and un-maintainable way, you can do what I do these days and take a staged approach.
No inline style attribute
Never create your css inline, by which I mean: <element style='color:red'> or even <img style='float:right'> It's very convenient, but doesn't reflect actual selector specificity in a real css file later, and if you keep it, you'll regret the maintenance load later.
Prototype with <style> instead
Where you would have used inline css, instead use in-page <style> elements. Try that out! It works fine in all browsers, so is great for testing, yet allows you to gracefully move such css out to your global css files whenever you want/need to! ( *just be aware that the selectors will only have page-level specificity, instead of site-level specificity, so be wary of being too general) Just as clean as in your css files:
<style>
.avatar-image{
float:right
}
.faq .warning{
color:crimson;
}
p{
border-left:thin medium blue;
// this general of a selector would be very bad, though.
// so be aware of what'll happen to general selectors if they go
// global
}
</style>
Refactoring other people's inline css
Sometimes you're not even the problem, and you're dealing with someone else's inline css, and you have to refactor it. This is another great use for the <style> in page, so that you can directly strip the inline css and immediate place it right on the page in classes or ids or selectors while you're refactoring. If you are careful enough with your selectors as you go, you can then move the final result to the global css file at the end with just a copy & paste.
It's a little hard to transfer every bit of css immediately to the global css file, but with in-page <style> elements, we now have alternatives.
In addition to other answers.... Internationalization.
Depending of the language of the content - you often need to adapt the styling of an element.
One obvious example would be right-to-left languages.
Let's say you used your code:
<img src="myimage.gif" style="float:right" />
Now say you want your website to support rtl languages - you would need:
<img src="myimage.gif" style="float:left" />
So now, if you want to support both languages, there's no way to assign a value to float using inline styling.
With CSS this is easily taken care of with the lang attribute
So you could do something like this:
img {
float:right;
}
html[lang="he"] img { /* Hebrew. or.. lang="ar" for Arabic etc */
float:left;
}
Demo
Inline CSS will always, always win in precedence over any linked-stylesheet CSS. This can cause enormous headache for you if and when you go and write a proper cascading stylesheet, and your properties aren't applying correctly.
It also hurts your application semantically: CSS is about separating presentation from markup. When you tangle the two together, things get much more difficult to understand and maintain. It's a similar principle as separating database code from your controller code on the server side of things.
Finally, imagine that you have 20 of those image tags. What happens when you decide that they should be floated left?
This only applies to handwritten code. If you generate code, I think that it's okay to use inline styles here and then, especially in cases where elements and controls need special treatment.
DRY is a good concept for handwritten code, but in machine-generated code, I opt for "Law of Demeter": "What belongs together, must stay together". It's easier to manipulate code that generates Style tags than to edit a global style a second time in a different and "remote" CSS file.
The answer to your question: it depends...
Using inline CSS is much harder to maintain.
For every property you want to change, using inline CSS requires you to look for the corresponding HTML code, instead of just looking inside clearly-defined and hopefully well-structured CSS files.
The whole point of CSS is to separate content from its presentation. So in your example you are mixing content with presentation and this may be "considered harmful".
In addition to the other answers, another concern is that it violates the recommended Content Security Policy from MDN, https://infosec.mozilla.org/guidelines/web_security#content-security-policy
The justification they use is that inline javascript is harmful, XSS, etc., but it doesn't justify why inline styles should also be disabled. Maybe someone can comment as to why, but until then, I'll just rely on appeal-to-authority and claim: it's a security best practice to avoid inline styles.
Code how you like to code, but if you are passing it on to someone else it is best to use what everyone else does. There are reasons for CSS, then there are reasons for inline. I use both, because it is just easier for me. Using CSS is wonderful when you have a lot of the same repetition. However, when you have a bunch of different elements with different properties then that becomes a problem. One instance for me is when I am positioning elements on a page. Each element as a different top and left property. If I put that all in a CSS that would really annoy the mess out of me going between the html and css page. So CSS is great when you want everything to have the same font, color, hover effect, etc. But when everything has a different position adding a CSS instance for each element can really be a pain. That is just my opinion though. CSS really has great relevance in larger applications when your having to dig through code. Use Mozilla web developer plugin and it will help you find the elements IDs and Classes.
I think that even if you want to have a certain style for one element, you have to consider the possibility that you may want to apply the same style on the same element on different pages.
One day somebody may ask to change or add more stylistic changes to the same element on every page. If you had the styles defined in an external CSS file, you would only have to make changes there, and it would be reflected in the same element in all of the pages, thus saving you a headache. :-)
Even if you only use the style once as in this example you've still mixed CONTENT and DESIGN. Lookup "Separation of concerns".
Using inline styles violates the Separation of Concerns principle, as you are effectively mixing markup and style in the same source file. It also, in most cases, violates the DRY (Don't Repeat Yourself) principle since they are only applicable to a single element, whereas a class can be applied to several of them (and even be extended through the magic of CSS rules!).
Furthermore, judicious use of classes is beneficial if your site contains scripting. For example, several popular JavaScript libs such as JQuery depend heavily on classes as selectors.
Finally, using classes adds additional clarity to your DOM, since you effectively have descriptors telling you what kind of element a given node in it is. For example:
<div class="header-row">It's a row!</div>
Is a lot more expressive than:
<div style="height: 80px; width: 100%;">It's...something?</div>
Inline CSS is good for machine-generated code, and can be fine when most visitors only browse one page on a site, but one thing it can't do is handle media queries to allow different looks for screens of different sizes. For that, you need to include the CSS either in an external style sheet or in an internal style tag.
In-page css is the in-thing at the moment because Google rates it as giving a better user experience than css loaded from a separate file. A possible solution is to put the css in a text file, load it on the fly with php, and output it into the document head. In the <head> section include this:
<head> ...
<?php
$codestring = file_get_contents("styles/style1.txt");
echo "<style>" . $codestring . "</style>";
?>
... </head>
Put the required css in styles/style1.txt and it'll get spat out in the <head> section of your document. This way, you'll have in-page css with the benefit of using a style template, style1.txt, which can be shared by any and all pages, allowing site-wide style changes to be made via only that one file. Furthermore, this method doesn't require the browser to request separate css files from the server (thus minimising retrieval / rendering time), since everything is delivered at once by php.
Having implemented this, individual one-time-only styles can be manually coded where needed.
According to the AMP HTML Specification it is necessary to put CSS in your HTML file (vs an external stylesheet) for performance purposes. This does not mean inline CSS but they do specify no external stylesheets.
An incomplete list of optimizations such a serving system might do is:
Replace image references with images sized to the viewer’s viewport.
Inline images that are visible above the fold.
Inline CSS variables.
Preload extended components.
Minify HTML and CSS.
Personally, I think the hatred of inline css is just ridiculous. Hardcore cult behaviour, people just sheepishly repeat "Separation of concerns!". Yes, there are times where if there is a repeating element and you will need repeated styling to use a class targeted from a CSS file, but most of the time it improves speed of development and CLARITY OF CODE to put the style inline, it's great if I can look at the code and see that there is a custom margin height, it helps me picture the HTML document as a whole, instead of some named class that gives me little insight into which styles will be applied.
So I will be the contrarian here and say that inline css is great and that people who scream at you for using it are just following what they have been told without actually giving it any original unbiased consideration.
Even though I totally agree with all the answers given above that writing CSS in a separate file is always better from code reusability, maintainability, better separation of concerns there are many scenarios where people prefer inline CSS in their production code -
The external CSS file causes one extra HTTP call to browser and thus additional latency. Instead if the CSS is inserted inline then browser can start parsing it right away. Especially over SSL HTTP calls are more costly and adds up additional latency to the page. There are many tools available that helps to generate static HTML pages (or page snippet) by inserting external CSS files as inline code. These tools are used at the Build and Release phase where the production binary is generated. This way we get all the advantages of external CSS and also the page becomes faster.
In addition to other answers, you cant target the pseudo-classes or pseudo-elements in inline CSS
We have created a template-driven artifact generator that provides an include file capability for any kind of text artifact -- HTML, XML, computer languages, unstructured text, DSV, etc. (E.g., it's great for handling common Web or manual page headers and footers without scripting.)
Once you have that and use it to provide "style" tags inside your "head" tag, the "separation of concerns" argument goes away, to be replaced by "we have to regenerate after every change to the template" and "we have to debug the template from what it generates". Those gripes have been around since the first computer language to get a preprocessor (or someone started using M4).
On balance, we think the meta-izing capability of either a CSS file or "style" tags is cleaner and less error-prone than element-level styling. But it does require some professional judgment, so newbies and scatterbrains don't bother.

Resources