Is there a proper and wrong way to format CSS? - css

When I first started writing CSS, I was writing it in an expanded form
div.class {
margin: 10px 5px 3px;
border: 1px solid #333;
font-weight: bold;
}
.class .subclass {
text-align:right;
}
but now I find myself writing css like this: (Example from code I'm actually writing now)
.object1 {}
.scrollButton{width:44px;height:135px;}
.scrollButton img {padding:51px 0 0 23px;}
.object2 {width:165px;height:94px;margin:15px 0 0 23px;padding:15px 0 0 10px;background:#fff;}
.featuredObject .symbol{line-height:30px; padding-top:6px;}
.featuredObject .value {width:90px;}
.featuredObject .valueChange {padding:5px 0 0 0;}
.featuredObject img {position:absolute;margin:32px 0 0 107px;}
and I'm beginning to worry because a lot of the time I see the first form done in examples online, while I find the second form a lot easier for me to work with. It has a lower vertical height, so I can see all the classes at a glance with less scrolling, the tabulation of the hierarchy seems more apparent, and it looks more like code I'd write with javascript or html. Is this a valid way of doing code, or to keep with standards when putting it online should I use the vertical form instead?

Well, here is what say the most :)
summary:
css-tricks.com ran a poll. By a margin of roughly 3 to 1, most people preferred multi-line over single line css styles.

I personally prefer the first style. I like things that are easy to read and I don't mind scrolling. The dense nature of the second style slows down my reading, my ability to pick out the items that I'm interested in.
There certainly are trade offs to be considered with CSS due to the file size. CSS can be compressed. I find the size of CSS files to be the least of my worries with the sites I've built so far.
Ultimately, the important thing is that whichever style you choose to use is to be consistent. That consistency will make your life simpler when you have to update your CSS or when another developer has to update your CSS.

Indicating the hierarchy using indentation is not a bad idea. However, you should be careful that you don't fool yourself. In your example, you may be assuming that .scrollButton is always within .object1. But CSS doesn't obey that rule. If you used a .scrollButton class outside of .object1, it would still get the styles.

I dont know about you but I like the vertical mode during dev as it is far more easier to read for me.
However, in prod, you wanna compress your css to reduce payload and hence, the second style makes sense. Mostly, you would be using some CSS compressor to do this.

i like to write css in multi line. because this is easier to write and read. we can find error as early as possible and a look of view is nice with indentation . mostly when a designer work with css and gave to developer to develop site than developer can understand easily.
so i think multi line css is better way to work.

I personally find both of your examples hard to read, especially the second one.
Multi-line is easier to follow, and indentation can be misleading as CSS is not necessarily applied in that way. Your indentation may lead you to believe it is.
I prefer the basic tried and true method of multi-line, with reasonable/logical order:
div.class
{
margin: 10px 5px 3px;
border: 1px solid #333;
font-weight: bold;
}
.class
{
text-align: center;
margin-left: 10px;
}
.class .subclass
{
text-align:right;
}
Takes up a little more space and requires a little scrolling to take in, but is easy to follow. Those worried about optimization can always use CSS shrinking tools for production CSS files.
In the end as long as you are very consistent with your work and across a team (if applicable) then no answer is more correct.

I prefer the second style, but be aware that it's a style. In the same way that some people prefer
function (arg)
{
body();
}
to
function(arg){
body();
}
I don't get it, myself. The argument is "it's easier to read", and my response is consistently "... for you". As a note, I get the feeling that this is why so many examples use the more-whitespace version; it has the reputation (if not confirmed property) of being easier to read.
Pick the one you like and stick with it. If you have a team to cooperate with, try to get to consensus, or barring that, write some auto-formatting scripts and stay out of each other's way. It's not like it's terribly difficult to mechanically transform one into the other.

The style you write in is your choice(I prefer multi line) but as Rajat said you want to remove any extra whitespace after dev. Anytime you can reduce file size and payload you are doing your site and your visitors a favor.

I think it also depends on your editor. I use multi line formatting and condense every definition with Vim's folding (I set up folding marks to be { and }) so I get one tag/class/id per line, expandable when needed.
Using comments to identify "sections" I get a very clean look with minimal vertical scroll while maintaining the readability of multi line on expanded definitions.

I just want to point out that Textmate has an option that allows you to easily switch between these two styles by selecting an area and pressing Ctrl-Q/Ctrl-Alt-Q to expand/collapse. As a consequence I have come to find that I prefer my CSS collapsed unless I am writing or deep debugging a specific section. But, with the ability to easily switch between he two I see that both ways are useful for different circumstances.

I prefer multiline right up until we deploy. At that point I want it minified.

Perhaps, when you have multiple selectors and one rule, like this:
#header li a, #header li span {
display:inline-block;
}
So, I prefer to do:
#header li a,
#header li span {
display:inline-block;
}

I've always liked this style:
#something1 {
color : #ffffff;
background : #000000;
}
#something2 {
color : #000000;
background : #ffffff;
}
But yo answer your question: As long as it functions the same way, there is no "proper" or "best" way to format your code. Use a style your comfortable with.

Related

What's the proper way to code repeating CSS

Say throughout my site, there is multiple places that I want my text to be coloured #f00
If I want to target them, should I make one declaration to target everything at once e.g.
a, .color, h2 {
color: #f00
}
OR, should I "color" them when I am targeting them anyway e.g.
a {
padding: 5px;
color: #f00;
}
.color {
background: #333;
color: #f00;
}
h2 {
font-size: 20px;
color: #f00;
}
I'm never sure which to do, sure, the first part in this isntance looks like less code, but then I am referencing tags more than I need to. But on the other hand, I am using color: #f00 3 times instead of just the once.
I appreciate neither are "wrong", I was just wondering if one is quicker, more semantic or what.
Note: This isn't my code in any site, just a quick mock up. I'm looking for an answer on a bigger scale
The first one is the preferred method. Typically, a developer's goal is to minimize CSS size to encourage faster loading. Your first example surely takes up less space as a result of combining the classes together.
I think this is mostly a stylistic choice, but I'll tell how I approach it.
If there's something all these cases have in common that implies that they should always have the same color, then group them together.
However, if there's something they have in common, that suggests that you should perhaps give that commonality a name, and make it a class name. Then assign the style to the class. This is good modularity.
If it's just by chance that they have the same color, and you're likely to change one without changing the others, use the second form.
Hope's answers is true, but unless there are a huge number of styles like this I doubt that it's going to have a noticeable impact on loading time.
I haven't played with LESS yet, I wonder if it optimizes this automatically.
The first option should be the best, in the sense that if you write less code, and that if you wanna change this color into another one everywhere, you'll have a single line to change.
But finally, this is more useful to use the second method.
If you still wanna change this color everywhere, event the simpliest editor will allow you to do it easily. But if you wanna change the color of a single div, you'll need to move your code.
A good practice (using the second method), is to reference all used colors at the top of your main css file (in comments), then you can easily pick one to search/replace all matches.

Is it bad to overwrite styles in CSS?

Sometimes we try to write the CSS Style Sheet with the less lines possible.
Let's look at this example:
Note: Previously borders where all width:1px, border-style:solid and border-color:#000
Scenario:
We want to change:
the width of: R, L and B to 0px
the border-color of: T to #ddd
Code Used:
border:0 solid #ddd;
border-top-width:1px;
What did the code above did unnecessarily?:
changing the border-color of: R, L and B (3 actions)
changing the width of: T (1 action)
Here is the code with 0 unnecessary actions:
border-right-width:0;
border-bottom-width:0;
border-left-width:0;
border-top-color:#ddd;
The question is: should we sacrifice efficiency for less-code/readability?
The efficiency loss will not be measurable, if any.
It is always better to write well readable code.
And in the end you first example's file size is less, so downloading the CSS is quicker.
should we sacrifice efficiency for less-code/readability?
Yes! If you want efficiency, compress your code, but always have a fully readable, easy to modify, clear and to-the-point, source version.
And it's usually best to have zero inline styles. If it's just one element, give it an id and put the style for it in your CSS file.
In my opinion, rewriting CSS is part of CSS.
As for efficiency, I don't think you will notice a measurable difference (with the exception of download times) in between the two.
What is important is to be consistent, and make your code readable.
As for your example, I would have done:
border:none;
border-top:1px solid #ddd;
Simply because I feel that makes it more readable
I think you're asking the wrong question. The sample you provided is not going to result in much of a difference at all between download-times or the time it takes to render the page. I think any web-developer's main focus should be on making the code easily readable to at least themselves, and preferably to others.
I would have done this:
border-width: 1px 0 0 0;
border-style: solid; /* may not be necessary as many browsers use this as default */
border-top-color: #DDD;
It's short, and not very cryptic as to what the display is like, and doesn't do anything unnecessary.
As for compression: not sure what the authors meant by it but if you minify the code, the browser at the other end won't "unminify" it to read it like we would want to. Empty space is ignored anyway, and if not there, that probably even speeds up the parsing...

Replacing CSS classes with more generic ones

I'm currently working on refactoring a large amount of CSS, and a common trend I'm seeing is that several classes have been created for a very specific item on a page. Rather than trying to describe what they do, the classes are named things like "PressReleaseText", or "SpecLabel", etc. Most of these just define one item, like a font-size or a color.
I'm wondering if it would be better to just create several utility classes, like .fontSize140 {font-size: 140%;}, .bgColorWhite{ background-color: white;}, and utilize those in place of all the duplication occurring across the current set of classes.
Are there any drawbacks to doing this? The point where it becomes blurry is if a current class has 3 attributes set, like color, background color, and font size, and I already have generic classes for all three of those, would my class definition in the html just look something like class="white bgColorBlue fontSize140". That just seems excessive.
This is absolutely a horrible practice. It's 10x worse than the current class names that you're trying to replace. Consider the following class names:
fontSize140
bgColorWhite
marginTop150
These are obviously very descriptive class names. The problem is that they describe the styles behind the class, not the content that it styles. While this can be easier to read in HTML, it will be a complete nightmare in the future when and if you decide to make even the tiniest redesign.
For example, let's say we just applied these three classes to a block of text. It has a font size of 140%, a white background, and a top margin of 150px. That's all fine--until we decide that it needs to be 90% font, a blue background, and no top margin. Now, not only do you have to change the CSS declarations, you have to either:
(1) edit every instance of the class in the HTML to be fontSize90bgColorBlueNoTopMargin or whatever; or
(2) leave the class name alone and leave an extremely confusing class name in the HTML.
Either way it will be a massive pain for you in the future, whereas the current class names (e.g., specLabel, pressReleaseText) appropriately describe the content that they style; their styles can be easily changed without affecting the content inside of them, and thereby never affecting the name of the class.
Part of the point of CSS is to separate the content from the presentation, to make it easier to alter the presentation without altering the content. If you have class="white bgColorBlue fontSize140" all over the place, you have defeated this goal; you might as well just go with style="color: white; background-color: blue; font-size: 140%". Your classes should say what you mean not what you want it to look like.
If you find yourself repeating certain settings for lots of classes, like the following
.PreReleaseText { font-size: 140% }
.SpecLabel { font-size: 140%; background-color: white }
.SomeOtherThing { font-size: 140% }
You can instead combine several of them into one single rule
.PreReleaseText, .SpecLabel, .SomeOtherThing { font-size: 140% }
.SpecLabel { background-color: white }
If you really do just have several classes that are synonyms of each other, you might want to think about why that is. Why are all of those styled the same way? Is there some class name you can come up with that encompasses all of those uses? Or is it just incidental that they happen to be styled the same way? If it's just incidental, then they should have separate rules, so you can easily update the styles of each class independently. If there is some unifying theme, then perhaps you should merge them into a single class.
Remember to consider what will happen in different media, or in a redesign. Imagine that the company is bought out, and you want to change the color scheme to match the new corporate colors, without doing a full redesign. If you have a .bgColorWhite class, but only some of the things labelled with that class should change to a new color in the redesign, you'll have to go through all of your templates and markup again to separate out the classes, but if you labelled them with more meaningful classes, you may be able to just tweak the colors in the appropriate classes.
These are some general guidelines; you should always use what works best for you. If you had a more specific example, I might be able to suggest a better way of refactoring your classes for your specific need.
There is not a right and wrong way to do this as far as I'm concerned. It depends on knowing how often you'll reuse things and what makes it easiest to understand the CSS. I've often seen those general things like .fontSize140 end up causing problems later on when you have to make changes. I prefer in most cases to group classes but keep the individual names.
So I might have
.Thing1,
.Thing2,
.Thing3 { font-size:14px; }
.Thing1 { font-weight:bold; }
.Thing2 { font-size:italic; }
Instead of having
.font14 { font-size:14px; }
And then still needing the .Thing1 and .Thing2 clases.
That was I can always change the CSS easily later without having to worry what is sharing that common .fontSize140 for example.
I would stay away from getting too general like .fontSomeSize. That said i generally try and use classes that define things as logical "types" or "objects" for example .ruled-list or .summary.
Why don't you try something like this:
Use a css preprocessor like sass.
/* define app/website colors */
$main-color: #223c61;
$secondary-color: #2954a2;
$accent-color: #4cceac;
/* some example css classes */
.text-main { color: $main-color; }
.bg-secondary { background-color: $secondary-color; }
.bg-accent { background-color: $accent-color; }
/* define app/website spacings */
$spacing-xs: 10px;
$spacing-sm: 15px;
$spacing-md: 25px;
$spacing-lg: 35px;
/* some example css classes */
.padding-up-xs { padding-top: $spacing-xs; }
.padding-down-lg { padding-bottom: $spacing-lg; }
.margin-left-md { margin-left: $spacing-md; }
The above code has generic css classes, but it is not bound to a specific value. For some very specific styling, you can always make a custom css file to account for that.
I see a lot of people using custom margins and paddings throughout their css. See the code below.
.blog-post-sidebar-right { margin-top: 14px; }
.news-post-bottom-text { margin-bottom: 23px; }
As a rule of thumb, I always use 4/5 predefined margins and paddings. And not some arbitrary number you make up on the fly.
So why not define generic css classes to use them. I took this same idea an applied it to all of my css. Now I can have the same code base in every project.
Because you now use a css preprocessor, it's easy to maintain, flexible and easy to extend.
Im not saying this is the best option, but it does the job for me.

Is there a reason CSS doesn't support applying styles from within styles?

In CSS2 and even in the upcoming CSS3, I can't find something that would be completely natural and time-saving - applying CSS styles from within other styles, rather than from HTML.
For example:
.awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
.alwesome-image; // or something like that - this is similar to a function call in a functional language
padding: 2px;
}
Oftentimes, one doesn't have access to generated HTML, so modifying CSS is the only choice.
This sort of inheritance support would make life a lot easier because we'd be able to treat CSS rules as "functions" and reuse the code rather than duplicate it.
Or am I missing something and CSS does support this (I've never seen it before?) or plans on supporting it? Enlighten me please.
Edit: Consider another example which shows that declaring .awesome-image, .super-awesome-image {common rules} is not elegant:
.border5 {
border-radius:5px;
-moz-border-radius:5px;
-webkit-border-radius:5px
}
I would much rather not pile up every other class that would want to have a border radius in the same definition. Alas, that's what needs to be done without functional support (I mentioned a lot of times there's only access to the CSS file and not the HTML itself).
In CSS, this is achieved as follows:
.super-awesome-image, .awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
Styles can be applied to multiple classes at once, which allows for easy inheritance.
There has been much debate as to whether CSS should be given functional programming techniques or layer inheritance, but this style of class inheritance will probably remain.
EDIT:
If you can generate styles with php, such inheritance should be quite doable.
Check out these scripts (which mostly deal with CSS variables, but may do more):
http://www.shauninman.com/archive/2005/08/05/css_variables
http://www.joesapt.net/2005/09/03/08.46.34
http://interfacelab.com/variables-in-css-via-php/
http://www.conditional-css.com/
It would make recursion possible (which would mean parsers would need to be able to recover from it)
Multiple rule-sets can use the same selector, so which one would apply? Or would all of them?
You can achieve what you want with:
<img … class="awesome-image super-awesome-image">
or
.awesome-image,
.super-awesome-image {
border: 1px #000 solid;
margin: 2px;
}
.super-awesome-image {
padding: 2px;
}
It kind of does support what you're suggesting, via the Cascade and inheritance. These are essential parts of CSS to understand, but they're sometimes a bit, er, idiosyncratic ...
I think the problem you mention is valid, but in those situations where the web programmer is completely separate from the web designer, it puts the onus on the initial project management to ensure both do what they're meant to. It's obviously a good philosophy to separate function and style, but there will always have to be some kind of link between the 2 and that is carried out by specifying the external CSS file(s). That's the reason it's important to define Id's and Class's carefully and always factor in some scope for change, i.e never make your CSS too general and always define ID's and Class's in the HTML for elements even when you're not styling them right now. It's a fine line to walk though between being pedantic and being careful, but then trying to think 6months/1year/5years ahead always would be ;)
This has always been my own personal approach.
I think "mixins" in LESS or SASS do exactly that.
As for why CSS itself doesn't do that, I don't know. First, I'd like to know why CSS doesn't give me a sane way to vertical align my content, or to shrink-fit a container (with floats), or to override overflow:hidden clipping for selected elements, or to do absolute positioning in relation to opposite edges, or ... and a lot of other things.
Your idea sounds nice, though.

CSS 'schema' how-to

How does one go about establishing a CSS 'schema', or hierarchy, of general element styles, nested element styles, and classed element styles. For a rank novice like me, the amount of information in stylesheets I view is completely overwhelming. What process does one follow in creating a well factored stylesheet or sheets, compared to inline style attributes?
I'm a big fan of naming my CSS classes by their contents or content types, for example a <ul> containing navigational "tabs" would have class="tabs". A header containing a date could be class="date" or an ordered list containing a top 10 list could have class="chart". Similarly, for IDs, one could give the page footer id="footer" or the logo of the website id="mainLogo". I find that it not only makes classes easy to remember but also encourages proper cascading of the CSS. Things like ol.chart {font-weight: bold; color: blue;} #footer ol.chart {color: green;} are quite readable and takes into account how CSS selectors gain weight by being more specific.
Proper indenting is also a great help. Your CSS is likely to grow quite a lot unless you want to refactor your HTML templates evertime you add a new section to your site or want to publish a new type of content. However hard you try you will inevitably have to add a few new rules (or exceptions) that you didn't anticipate in your original schema. Indeting will allow you to scan a large CSS file a lot quicker. My personal preference is to indent on how specific and/or nested the selector is, something like this:
ul.tabs {
list-style-type: none;
}
ul.tabs li {
float: left;
}
ul.tabs li img {
border: none;
}
That way the "parent" is always furthest to the left and so the text gets broken up into blocks by parent containers. I also like to split the stylesheet into a few sections; first comes all the selectors for HTML elements. I consider these so generic that they should come first really. Here I put "body { font-size: 77%; }" and "a { color: #FFCC00; }" etc. After that I would put selectors for the main framework parts of the page, for instance "ul#mainMenu { float: left; }" and "div#footer { height: 4em; }". Then on to common object classes, "td.price { text-align: right; }", finally followed by extra little bits like ".clear { clear: both; }". Now that's just how I like to do it - I'm sure there are better ways but it works for me.
Finally, a couple of tips:
Make best use of cascades and don't "overclass" stuff. If you give a <ul> class="textNav" then you can access its <li>s and their children without having to add any additional class assignments. ul.textNav li a:hover {}
Don't be afraid to use multiple classes on a single object. This is perfectly valid and very useful. You then have control of the CSS for groups of objects from more than one axis. Also giving the object an ID adds yet a third axis. For example:
<style>
div.box {
float: left;
border: 1px solid blue;
padding: 1em;
}
div.wide {
width: 15em;
}
div.narrow {
width: 8em;
}
div#oddOneOut {
float: right;
}
</style>
<div class="box wide">a wide box</div>
<div class="box narrow">a narrow box</div>
<div class="box wide" id="oddOneOut">an odd box</div>
Giving a class to your document <body> tag (or ID since there should only ever be one...) enables some nifty overrides for individual pages, like hilighting the menu item for the page you're currently on or getting rid of that redundant second sign-in form on the sign-in page, all using CSS only. "body.signIn div#mainMenu form.signIn { display: none; }"
I hope you find at least some of my ramblings useful and wish you the best with your projects!
There are a number of different things you can do to aid in the organisation of your CSS. For example:
Split your CSS up into multiple files. For example: have one file for layout, one for text, one for reset styles etc.
Comment your CSS code.
Why not add a table of contents?
Try using a CSS framework like 960.gs to get your started.
It's all down to personal taste really. But here are a few links that you might find useful:
http://www.smashingmagazine.com/2008/08/18/7-principles-of-clean-and-optimized-css-code/
http://www.smashingmagazine.com/2008/05/02/improving-code-readability-with-css-styleguides/
http://www.louddog.com/bloggity/2008/03/css-best-practices.php
http://natbat.net/2008/Sep/28/css-systems/
Think of the CSS as creating a 'toolkit' that the HTML can refer to. The following rules will help:
Make class names unambiguous. In most cases this means prefixing them in a predicatable way. For example, rather than left, use something like header_links_object2_left.
Use id rather than class only if you know there will only ever be one of an object on a page. Again, make the id unambiguous.
Consider side effects. Rules like margin and padding, float and clear, and so on can all have unexpected consequences on other elements.
If your stylesheet is to be used my several HTML coders, consider writing them a small, clear guide to how to write HTML to match your scheme. Keep it simple, or you'll bore them.
And as always, test it in multiple browsers, on multiple operating systems, on lots of different pages, and under any other unusual conditions you can think of.
Putting all of your CSS declarations in roughly the same order as they will land in the document hierarchy is generally a good thing. This makes it fairly easy for future readers to see what attributes will be inherited, since those classes will be higher up in the file.
Also, this is sort of orthogonal to your question, but if you are looking for a tool to help you read a CSS file and see how everything shakes out, I cannot recommend Firebug enough.
The best organizational advice I've ever received came from a presentation at An Event Apart.
Assuming you're keeping everything in a single stylesheet, there's basically five parts to it:
Reset rules (may be as simple as the
* {margin: 0; padding: 0} rule,
Eric Meyer's reset, or the YUI
reset)
Basic element styling; this
is the stuff like basic typography
for paragraphs, spacing for lists,
etc.
Universal classes; this section
for me generally contains things
like .error, .left (I'm only 80%
semantic), etc.
Universal
layout/IDs; #content, #header,
or whatever you've cut your page up
into.
Page-specific rules; if you
need to modify an existing style
just for one or a few pages, stick a
unique ID high up (body tag is
usually good) and toss your
overrides at the end of the document
I don't recommend using a CSS framework unless you need to mock something up in HTML fast. They're far too bloated, and I've never met one whose semantics made sense to me; it's much better practice to create your own "framework" as you figure out what code is shared by your projects over time.
Reading other people's code is a whole other issue, and with that I wish you the best of luck. There's some truly horrific CSS out there.
Cop-out line of the year: it depends.
How much do you need to be styling? Do you need to change the aspects of alomost every element, or is it only a few?
My favorite place to go for information like this is CSS Zen Garden & A List Apart.
There are two worlds:
The human editor perspective: Where CSS is most easily understand, when it has clear structure, good formatting, verbose names, structured into layout, color and typesetting...
The consumer perspective: The visitor is most happy if your site loades quickly, if it look perfect in his browser, so the css has to be small, in one file (to save further connections) and contain CSS hacks to support all browsers.
I recommend you to start with a CSS framework:
Blueprint if you like smaller things
or YAML for a big and functional one
There is also a list of CSS Frameworks...
And then bring it in shape (for the browser) with a CSS Optimizer (p.e. CSS Form.&Opti.)
You can measure the Results (unpotimized <-> optimized) with YSlow.
A few more tips for keeping organized:
Within each declaration, adopt an order of attributes that you stick to. For example, I usually list margins, padding, height, width, border, fonts, display/float/other, in that order, allowing for easier readability in my next tip
Write your CSS like you would any other code: indent! It's easy to scan a CSS file for high level elements and then drill down rather than simply going by source order of your HTML.
Semantic HTML with good class names can help a lot with remembering what styles apply to which elements.

Resources