Do you write and manage large CSS files? Ever get tired of scrolling up and down in search of a specific rule or set of rules? The CSS files I work with for client projects are often quite long, requiring constant scrolling up and down several screen’s worth of text to alter rules or add new ones. While working on a current project, I just made a tiny little addition that makes finding what I want almost immediate.
Grouping your CSS rules
I briefly touched on CSS organization a couple months ago. As a bit of background, if you’ve ever taken a look at any of my style sheets, you’ve probably noticed that I always divide them into key sections. In every project I create, I typically have sections in the CSS broken out for the following:
- Header
- Structure
- Nav
- Search
- Headings
- Lists
- Forms
- Links
- Misc
When I was learning CSS in 2002 before the Wired News redesign, I devised my own means of using commented text and a series of dashes as headings to make these sections easily distinguishable:
/* Navigation
----------------------------------------------- */
This makes it fairly easy for me — or a client who takes over the files — to find certain rules, or to know which rules affect a relevant portion of the design. Even more importantly, this method of organization saves a lot of time when troubleshooting any style sheets I’ve written, especially for older projects where memory of how a project was built might be fading.
Finding those sections quickly
So how to find rules quickly when you’re working? Some apps allow you to set markers in documents, allowing quick key-command access to that section. Great if you’re into that kind of thing, but it can get tedious to do with every new CSS file.
You could also do what I’ve been doing for the last few years: use your text editor’s FIND
command to do a quick search for a certain block of text. But if your style sheets are anything like mine, a generic search like “nav” or “h2” might point to several places in the document, requiring several FIND NEXT
s (or many) to actually find what you’re looking for.
A fictitious, but even better example of FIND
not finding what you want immediately: Say you have a section of your site you’ve abbreviated with the acronym “RDE”. So you label a portion of your CSS with:
/* RDE
----------------------------------------------- */
Great. So you can easily see the rules that apply to the RDE section. Except that if you want to use FIND
to zoom to that section, you quickly notice that your text editor finds every instance of the following property:
#nav {
float:left;
width:182px;
border-top:1px solid #911;
}
A simple fix: Flags
As I discovered yesterday, if I add a simple flag immediately before the commented header text — like the “=” character, one that’s not used in CSS or class/id syntax — I have a simple text-based hook for finding (and zooming to) that section header immediately. So a quick FIND
for “=rde” yields the following:
/* =RDE
----------------------------------------------- */
And I’m right where I want to be with a few keystrokes. No more finding redundant instances of that string. The “=” flag doesn’t even need to be placed before the first word. On a current project, I have several sections whose label begins with “MISC:”. So I place the flag next to a more unique word in the label:
/* MISC: =Lists
----------------------------------------------- */
…which allows me to quickly zoom to that section for generic/default list styles by doing a FIND
for “=list”.
Of course, this tip is only helpful if you’re diligent about keeping rules organized into discrete sections when working with large style sheets.
Next tip will center around how I choose to break out my sections, the order of those sections in the entire document, and how to decide which rules get placed in which sections when there’s more than one choice.
This tip is a godsend Doug. I’ve been putting in the headers for a large CSS file I’ve been working on for the last couple of months and hated having to scroll thorugh it as well. Thanks for sharing it.
Great tips! A co-worker and I are in the middle of creating a set of standards for writing CSS files, and this is definitely some great insight.
I have the most trouble when having rules that overlap sections, so I’m really looking forward to your next tip.
Such a simple, yet invaluable tip. Thanks Doug.
I’ve often wondered about ways to organize my CSS, and which way best suits the individual project. Something that I’ve been toying around with in some sample sites was creating modular stylesheets. It’s similar in concept to your method of breaking the layout and color into two different stylesheets and then importing them in to create the finished site. Each module has a distinct section it applies to and is then imported into the page. It takes more effort to keep everything seperated, but it gives you the ability to change just sections of the site at a time. Rather than opening up one, or two files, that control everything and then having to search for that commented header, all you have to do is open the precise file that controls that one section you want to work on.
Another option for organizing your CSS might be to group rules by objects. So all your headers are together, all your lists are together, all your different image classes are together, so that you can view what rules overlap with one another and simplify the rules to just what you need and let inheritance control the rest.
Brilliant!
@Steve (#4):
Another option for organizing your CSS might be to group rules by objects. So all your headers are together, all your lists are together, all your different image classes are together…
Exactly. And this is what I do for generic rules that aren’t tied to any one section. I label them with the “MISC:” headers mentioned above. I certainly do that for headers, lists, form elements, etc.
But over the years, I’ve discovered it’s easier (for me, anyway) to keep rules grouped together if they apply specifically to a certain module or type of content on the site. That way, when I want to work on the header, I don’t need to go looking through multiple sections of the site. This is precisely the type of thinking I plan to cover in more detail for the next tip.
P.S. Oh, and as Molly reminded me at a recent conference, it’s *elements* we need to refer to in this instance. An
object
is already an existing and specific HTML element. So to avoid confusion, even when talking about style sheets, it’s *elements* we’re styling and grouping, not objects — unless we’re actually talking about the<object>
element. A common mistake I make all the time.Brilliant! (Clink!)
Couldn’t you just search for “* WORD”? Or “: WORD” for the sub-labels?
As for your section delimiters, I use a similar technique. Stars instead of dashes, but it looks almost the same. I was probably influenced by one of your stylesheets at some point, if so, thanks for that… it’s a life saver ;)
Stylesheet organization is definately a headache.
I tend to group things a little differently then you’ve outlined here, but I do still find it true that *not* grouping on tag does make the difference (I generally gropu by color palete & typography, then structure, then specific content block/elements/widget definitions leaving any explicit declarations or overrides last.
Another tip I find very useful is to be verbose in my use of selectors. While the following two selectors may always match the same thing:
blockquote
#content blockquote
I’ll use the latter because it helps me read thigns wehn in a group of rules. Similar with these two groups:
ul {}
ol {}
li {}
ul {}
ol {}
ul li,
ol li {}
I’ll use the second grouping because it allows me it scan higerarchy and the cascade rules quickly when I go back over a style sheet.
A quick tip for searching with the “Find” command in any text file, and avoiding returning several results: if you want to find RDE, type ” RDE ” in the search field (note the spaces before and after). This way you’ll only find it where it is as a single word and not part of a word (like border). Though your solution is way better for managing CSS files, this little tip can help you in other situations.
I’ve been using skEdit for my web page coding and it has a nifty navigational feature that allows you to quickly browse a drop down menu and select the tag you want to jump to — very handy in large css files! My favorite, however, is how CSSEdit handles navigation — a large side bar with each tag color coded based on if it’s an id or class. Much more simple than skEdit, but overall skEdit is a more full featured app and I’ve learned to adapt.
I do think it’s very important to standardize the way your write code and to apply those rules you invent for yourself to all projects. This is not only important with tag names and commenting, but even down to the order in which you place properies into a declaration block. Doing the same thing all the time makes scanning your code much easier; it also allows you to make changes to any project with a minimum of fuss.
I saw your method of CSS commenting and have actually been using it for a while now. Interesting idea about the flags, thanks for the tip!
I use both skEdit for HTML and CSSEdit for stylesheets. CSSEdit is highly undervalued given its simplicity, speed, and organizational abilities. When you couple CSSEdit with a hierarchy structure as Doug’s described (I ripped off your dashed-headings over a year ago, thanks Doug!) — you have a real winner.
Brilliant! Man, so simple but so effective. I’ve been wearing out my mouse button on “find nexts” for years it seems. I’ve always commented out the sections like that but never thought of a flag. Boy, it’s the simple things in life… :)
Why not use an editor capable of folding? I use vi, and by placing folding markers I can fold subsections and easily have a TOC-like view of the CSS by folding the whole document.
Even if vi is a bit too extreme (it’s geek-friendly and regular user-unfriendly), there are heaps of editors capable of folding text sections.
A fold looks something like this:
/* Header {{{ */
Header css rules
/* }}} */
And folded looks like:
— Header (29 lines) ———–
Other than that, I use a similar approach, grouping by defaults, then layout then specific look and feel and leaving typography last.
Great tip Doug. I wish there was some nifty syntax to collapse sections of your CSS (maybe this could be a feature of an IDE?). Similar to collapsing nodes of an XML document.
You can do this in C# and it would be a huge space saver for CSS as the files *do* get quite large.
BTW, I had a heck of a time loading this article through Bloglines. I ended up just going to your site directly.
I have been working on a css file that is several hundred lines long. The process is very tedious and somewhat annoying at times, specially when you are trying to make a quick change and show to the client/boss and it takes 30 seconds just to find each rule.
Anyways, thanks for the tip Doug! Glad to hear there are more cooking.
I can’t believe this deserved it’s own post. Talk about a no-brainer. But, as a software developer, you learn stuff like this right away or you die.
These divisions are useful. An alternative to dividing up the sections with this =SECTION label is to place the sections in separate files and to have a master css file with import statements. This technique is especially useful because you can mix and match existing mini-css ‘modules’.
If you use an editor that has a tree view of your project files it is really easy to switch between the css files rather than searching through the while for =SECTION hooks.
Great tips Doug! I’ve been finding myself endlessly scrolling to edit some of my CSS files. I think with a little discipline, I can use your suggestions to make my life easier. Many thanks.
Thanks for the tip Doug, this is a real time saver!
Not wanting to be provocative, but… the initial objective should be to avoid CSS files that are too long in the first place. I’ve found there’s a tendency to keep adding rules to cope with particular new situations – poor discipline as one goes along – and which could have been avoided had I adopted more careful planning from the outset.
So another aspect of this is deciding at what point during a site’s normal navigation sequence the various style rules are loaded for optimal performance. For example, if you have a minor page with special requirements, then consider loading the extra rules only when that page is requested.
An approach that tackles the cause before the symptom…
I agree with Patrick, although I’ve certainly been guilty of bloated CSS files for projects that were time-critical…
I usually just mark sections like /*section*/ then just search for /*whatever; also, I like the idea of using a folding editor that someone mentioned; it brings back memories of doing coding in school. Maybe it’s time to switch software…
@Patrick (#22):
Not wanting to be provocative, but… the initial objective should be to avoid CSS files that are too long in the first place.
But that’s only *if* they can be avoided. I adhere to your theory, Patrick, and also believe in keeping code as simple and optimized as possible. But more complex sites require more complex code. A simple-view theory won’t always hold water.
We’re not just talking about simple 3-template blogs here — we’re getting into large sites with all kinds of content that can go on any page. Sometimes those types of sites need lots of CSS that can handle multiple possibilities on the fly without the client needing to go back and remember which set of CSS files they need to import just to add one extra content module to the page.
If a whole chunk of rules can be broken off, placed in a separate CSS file, and only loaded for a section of the site (such as the Portfolio here) then what you suggest is a possibility and sometimes a good idea. But we don’t always have the luxury of isolating content types to one section or one page.
CSSEdit actually lets you create the groups you described, and it creates a comment in the stylesheet to differentiate a group. Also, in the sidebar, you can toggle the group between a folder view (showing just the group name) and the regular view showing each rule. Very handy for when you want to keep your CSS editor’s window small but you have a long list of rules.
Thanks for the information…
Great tip! I’ll try to organize my style sheets this way. Much easier to see/edit.
Great tip Doug! Thanks a bunch for the info.
I’ll try following your method. It should save me a lot of searching.
Doug,
Thanks for the post. A pretty basic solution, but still good advice.
I wrote a shorter piece about this in the beginning of April at http://www.robertnyman.com/2005/04/06/i-improve-design/ (feel free to remove my link if you want to), describing how I usually do.
Something I’d prefer is if there were some class-like grouping in the CSS. For instance:
div#header{
a{
color:#F00;
}
ul{
list-style:none;
}
}
where those styles above would only affect the elements within a div named ‘header’.
Sure! I especially manage CSS content not only for me (and for a better future reading) but for the guy who will be coding after me someday…
I only use simple comment before each topic like:
/*
************************************************
le bloc de navigation gauche
************************************************
*/
But is there somebody using BBEdit Software? The “function” menu in the top left side of the window give you a ‘quick access to all the routines and functions in languages that BBEdit can parse’. It’s enough for me.
Have a nice day!
Also, I use Bradbury’s TopStyle for writing my CSS, which gives me the possibility to expand or collapse CSS rules by my choice.
To me, that’s great, since I can choose to only see the rules that I’m currently working with.
When my stylesheets start to go large I tend to look for ways to reduce tags, find places where I’m duplicating most of the same properties, find sections of the site that are similar enough that I could consider using the same class for each, etc.
I’ve found that the top-down approach has REALLY helped me keep my CSS organised. That is to say, writing all of the content first, then the XHTML, with appropriate classes or IDs where the content suggests it, etc. Oh sure, I nearly always have to add extra ids, wrapper divs, or some other code bloat to get things working in Ubiquibrowser 6, but it keeps things as lean as possible.
And I also use TextPad as a text editor with a macro to collapse each selector into a single line, and expand the one I’m currently editing. This has the added benefit of reducing the file size by getting rid of the whitespace, and seeing all of the selectors in a column is actually fast and easy to scan.
I keep meaning to organise better in my CSS files, like sorting the selectors alphabetically or something, but sometimes it’s hard to remember what one div ID is named, so organising by section seems to be the way to go.
I learned CSS by mimicking Zeldman’s early efforts, so I think I’ve also integrated his bad habits and missteps at times too. ;)
For small projects like my own blow I only use the normal
/* Headings */
For larger projects I use numbering, in the top of the file I have an appendix
/*
1.0 Headings
1.1 Search
1.2 Menu
etc
*/
In content part of the css file I then have
*/ 1.0 Headings */
h1 {bla bla bla}
etc
When I search the doc, I hit CTRL + F and hit 1.1 or similar. I try to use a numbering that do no conflict with any numbers I use in my css file. Works like a charm. :D
Aren’t there IDEs that does these kind of things
automatically for you?
The C# programming language has a “grouping”-feature
built in to the the language (#region) – maybe the
CSS standards commitee should take a look at that.
In my opinion, it’s more appropriate and even easier to sort your style sheet depending on the selectors, taking element selectors first (from block level to inline elements – taking into account associated elements like e.g. “ul” and “li” -, and from “more semantic” to “less semantic” – e.g. “span” elements last), then sorting attribute selectors.
Since the entire mechanism asks for specification (I once wrote it for a company, and it was not that trivial), I only want to demonstrate it with a few rules:
html {}
p {}
p#intro {}
p.error {}
ul {}
li {}
strong {}
span {}
Currently, I use exactly this sorting in the UITest.com style sheet as well
as in the style sheet of meiert.com. – It’s simple and absolutely sufficient.
Robert:
“div#header{
a{
color:#F00;
}
ul{
list-style:none;
}
}”
Use “div#header a” and “div#header ul” selectors for this.
I must say there are similar points in my CSS Organisation compaired to yours. I too group my sections. ‘Nav’, ‘Menu lists’, ‘forms’ etc. However, I do write my global (HTML selectors) first. The rest are add-ons. I also reuse a lot code. Working with css signatures helps a lot in this regard. Also I always write my rules on the same line as the selector. The order in which they’re placed becomes critical in relocating them.’float’ before ‘display’ and those before ‘margin’ and so on.
This makes the css less friendly to ‘hand over’ but I haven’t gotten any complaints. I do divide the CSS with commented titles. Make search in by scrolling easy.
I’ve even started indenting my CSS selectors. Others have found this very useful.
It’s an interesting subject, maybe I should just do my own post.
The CSSEdit way of building groups via a specific comments syntax is a great way to do it. I would love to see more applications adopt this format.
In BBEdit you can set markers and then go to them – that can be useful as well.
Cool Tip though Doug!
This is a brilliant idean and much easier to search and code your css. You are a genius!!!!!
One alternative is to have all your headings in caps, and just do a case sensitive search (since you CSS properties should be in lowercase, anyway). But I guess that is an extra thing to click, and forget to uncheck each time, though.
Jens,
Yes, I know how to do it correctly, and I hane no real problem with the way it should be.
But if I, for instance, were to have 10 rules in there, it would be nice with a grouping feature, similar to the
with
statement, and also a good way to structure my code.You already have an inherent flag inside of your heading. A search on /* rde would have resulted in finding what you wanted as well.
Another thing that I do is create a css style guide at the top of each css file like this:
/* css style guide */
/*————————————————–*/
/*
Sheet Organization——-
Global Properties (sub-category class properties)
Individual Element Properties
Within group arranged as follows:
Arranged in order of appearance within HTML
Arrange by most common usage:
Padding, Margin, Size, Positioning
Border, Background
Text entered with additional tab
Other Items————-
Section breaks 50 dashes
Indent everything related to text
ID space “{” and “}” on new line
COMMENT ID’s */
/* top right bottom left */
/*————————————————–*/
/* Global Setting */
/*————————————————–*/
I tend to forget if I don’t specify. Suggestions appreciated.
Cool Tips.
Thanks for sharing.
I’ve never been below trudging through your linked stylesheets for tips on CSS organization. I actually spent quite a bit of time in Jan-Feb writing a series on the topic and trying to refine my own methods. One idea I came up with that seems like it would work for certain projects is ordering layout selectors by order of appearence in the template and nesting them as they are on the page. It sounds confusing, but it worked really well for this test layout / css.
The final design didn’t turn out much different: Swamp Restaurant
I can’t believe it took almost a full day for the obvious to be pointed out by Alicia, “You already have an inherent flag inside of your heading. A search on /* rde would have resulted in finding what you wanted as well.”
Perhaps this doesn’t work in the editor you are using?
I don’t know whether this makes any sense, but I group the rules according to the three passes I make when I think about a new page:
1. layout/whitespace
2. text/fonts
3. the color scheme
Three different areas of the brain.
I agree with breaking out header, nav, search, and forms, but the links rules have to be coordinated with body text.
Alicia (#42) and Anon (#46):
You already have an inherent flag inside of your heading. A search on /* rde would have resulted in finding what you wanted as well.
I realize this, but 2 things:
1. I’ve always found the /* combination difficult to type quickly. = is much faster.
2. Doing a search for “/* rde” would require that the comment text start with “rde”. If I have labels in my CSS that look like this:
/* MISC: =Lists
----------------------------------------------- */
/* MISC: =Forms
----------------------------------------------- */
/* MISC: =Headings
----------------------------------------------- */
etc…
searching for “/* mis” wouldn’t point me to the right label immediately. But searching for “=lis” would. The custom flag allows flagging of any word within the commented header.
I’ve always found the /* combination difficult to type quickly. = is much faster
Ah, the joy of a keyboard with a number pad. “/” and “*” are right next to one another. Quick two-finger ‘da-dum’ on the keys, and we’re away…
Ridge – indeed, but not on laptops. :D
…not on laptops
No? That’s mine.
But I understand the point, and the tip Doug kindly shares with us. Just picking up on a technicality really. Now returning you to your scheduled programming…
Brilliant. I feel I’ve learned the most about CSS and ways of organizing it from this site. Thanks Doug.
Brilliant tip, however I wouldn’t use = for grouping… for just one reason; if I want to use other attributes than id and class for CSS identification.
div[rel=float] {
float: left;
}
Some text editors have features other than markers that might be helpful with this: grouping of sections and subsections of a document, with corresponding shortcuts for navigating among them.
For example, my editor of choice (vim) has a feature called folding that I’ve found very useful for grouping and navigating among sections of CSS (HTML, LaTeX, etc.) files. Folds also allow a lot of other things to be done: it’s an imperfect analogy, but working with folds is a bit like working in Word’s ‘outline’ view, including that it’s easy to expand, collapse, move, delete, etc. any fold and its contents, and that folds can be nested. It may seem a bit complicated at first, but it’s extremely powerful, and if you’ve already learned to use vim, chances are you’re not put off by something that at first appears complicated. :)
A very simple example:
/* blocks {{{ */
body {
font-family: "Bitstream Vera Sans", sans-serif;
}
/* end of block CSS }}} */
/* lists {{{ */
ul {
list-style-type: none;
}
/* end of list-related CSS }}} */
If your vim configuration contains ‘set foldmethod=marker’, the file will display like this:
+-- 7 lines: blocks ------------------------
+-- 7 lines: lists -------------------------
With the cursor over either fold, typing ‘zo’ and ‘zc’ in command mode will open and close the fold. In the vim gui (gvim), with ‘foldcolumn’ set appropriately, a mouse can also be used to expand and collapse folds. Needless to say, all of this can be very handy.
This is a great idea. I will definitely start using this system, it’s better than no commenting at all. Sorting through a huge list of results using “find next” has taken long enough.
I’m by no means a web developer, but CSS I have worked with from a developers perspective is generally quite “long and thin” as opposed to “short and fat”.
Surely what you need is some way of having a multi-column edit view on your nice widescreen mac displays?
I know a lot of editors (dev ide’s) will support this type of editing mode out of the box (i’m an MS developer, so I cant comment on any mac based editors).
Just a thought.
I try to break everything into modular stylesheets to keep things organized. I usually have 3 stylesheets for a site
basic.css = general css rules for the html elements
layout.css = all positioning rules, lots of IDs in here
typography.css = everything dealing with how text looks.
Usually in basic.css I zero out all my margins and remove list styles.
The directory structure is also important. I have a library sub directory in each directory with up to four directories in that graphics, css, javascript, and php. The graphics sub directory gets broken down further into images, backgrounds, widgets, and headers. There is, of course, a library directory in the root directory that contains the elements that are shared between the specific sections.
I got the idea from OS X. I love the fact that it has a systemwide Library directory that all users can use, and a user specific Library directory that is only accessable to that user.
Thanks for the tip Doug. Looking forward to your next tip.
I can’t believe so many people don’t already do this. Maybe because I use PHP but I always use “flags” to find sections.
I tend to use %= because it means nothing in any code I use.
EXAMPLE: %=NEWS_UPDATES
Honestly, I can’t be bothered with that much work while writing CSS. There are just a gazillion tools out there (Topstyle being my favorite) which let you browse CSS by IDs and classes. That’s what the computer is for, dammit :) Anyway, I don’t do much design work anymore, probably just as well.
I am nowdays organizing CSS into different files. I am calling in HTML file. main css file which includes others like:
@import url(“global/styles.css”);
@import url(“global/layout.css”);
@import url(“global/tables.css”);
@import url(“global/menus.css”);
@import url(“global/fonts.css”);
@import url(“global/forms.css”);
@import url(“global/teasers.css”);
Nice article! I’m just slowly coming to the realisation of commenting my CSS as it’s so difficult to find things in all the mess if you just keep adding to the bottom.
#62 won’t requesting all those CSS files add an awful lot of file requests meaning the page will be slower to load? I tend to do this just to separate out the hacks as necessary.
I have tried putting rules in separate css files and linking to all of them. I found I didn’t like it because it’s much easier to search by header like this than to open multiple sheets. I would much rather use a system of headers for sections to organize on one stylesheet than separate into 6 sheets. That becomes quite a pain.
Another thing I do is put the file name, description, and path commented at the top of the file, since I have a series of sites at my work that have a common stylesheet and specific stylesheets. Like this:
/********************************************************/
/********************************************************/
/***
/*** NAME: styles.css: common styles for all sites
/*** PATH: /assets/styles/styles.css
/***
/********************************************************/
/********************************************************/
Really helps when both files are called styles.css.
Wow, I can’t believe I’ve never thought of this. I’m always editing my stylesheets in Dreamweaver and find that I get lost once my CSS becomes hefty. Though I usually comment with things like “HEADER” and the like, using Dreamweaver’s find function does exactly what you mentioned above. But using flags would get me to the beginning of that section on the first try.
Such a simple little thing, yet very powerful. Thanks for the tip.
A couple of comments:
1) “My editor…” We forget that we’re not coding just for ourselves, but for the folks who will follow us on the project, and the bloke who’s trying to learn CSS by surfing source documents. If we rely on the editor to do this stuff, then everyone’s experience is going to be different. I realize that Kingsley (#61) is right on… this stuff is what a computer is made for (dammit!). But until we have some consensus on how to proceed, the only thing all computers have in common right now is FIND.
2) I am definitely going to start flagging my styles sheets going forward… but I have a suggestion of my own, too. As I’m coding, I put selectors and their ilk on their own line followed by the opening curly bracket. Then I arrange each property on its own line, indented one tab. I then close the rule with the closing curly bracket. Why do I do this? Because it makes scanning easy, as there’s nothing up against the left margin except for selectors. It looks like this (tabs changed to multiple spaces… damn HTML):
BODY {
background: none #EEEEEE;
color: #FFFFEE;
padding: 0px;
border: 0px;
margin: 0px;
font-family: sans-serif;
}
Now add flags, and I’m a very happy boy.
: )
3) There were a couple of comments about how this might play-out… I, for one, use BBEdit, and I have stationary that I use when starting an HTML or CSS document from scratch. I’m just going to edit my CSS stationary to include pre-formatted flags (and Heath’s nifty idea of a style guide header)… I’ll code between the flags, and remove the ones I don’t need when I’m done. But that’s just me.
4) Of course, this all boils down to something I’ve wondered for some time: where are our best practices? We have best practices for what web pages should do… but the closest we’ve come on the code seems to be “make it validate”, “make it small”, “comment your code”. Gack! I’d really like to see more discussion on this side of the mirror about how to best approach web coding/scripting/mark-up. … if this becomes a meme, Doug, we may be on our way.
I look forward to your next installment, Doug!
I like the approach of having multiple css files for specific sections of pages (I usually have different images folder for each css file as well) and then linking all needed css files from a master.css file. This way I can have “skins” folders, each one with its own bitmaps, layout and design css’, anthen if I want to switch “skin” sitewide I just update the references in the master.css file changing only the “skin” folder name in the path to the skin’s css files (all css files inside skin folders follow the same naming standard ie: “layout.css”,”design.css”,”forms.css”,etc), so in my master.css file I’ve got:
@import url(“skin_2005_01/layout.css”);
@import url(“skin_2005_01/design.css”);
So if I want to switch the entire skin I go:
@import url(“my_new_skin/layout.css”);
All controlled in one place.
I’ve found this architectural approach quite handy for large site, it is also optimal to replace the master.css file for a php or asp script that controls the skin switching, for instance.
Thanks for the great tip Doug! Since at my work we don’t create massively large stylesheets, I’ve usually organized my stylesheets like so:
all basic html tags first in some semblance of order
* {}
body {}
h1 {}
h2 {}
p {}
blockquote {}
small {}
strong {}
ul, ol {}
li {}
then the classes together w/ corresponding html tags
.callout {}
.callout h3 {}
.offer {}
.legal {}
.legal p {}
and finally all the ID’s together w/ corresponding html tags in order of appearance in the html doc
#nav {}
#nav ul li {}
#nav a, #nav a:link {}
#container {}
#container p {}
I know your tip will make our code mas easier to work with. Gracias! :) Look forward to your next tip!
Brilliant. I find that I have the same problem as well. I think I’ll go through my CSS file now and just make it much more clean. I do what you are saying in my actual HTML markup, but I never thought of porting the idea over to the souce file.
Thanks for the advice,
Raj
I really don’t understand why everyone complements this with ‘brilliant!’, ‘wow’, ‘nice’ and ‘great tip’! Is noone thinking for themselves? It’s not like this is rocket-science, anyone could have come up with this.. I’ve seen many stylesheets handling this in the same way. But now some ‘A-list’ blogger says ‘Hey! This is how I do it’ it suddenly becomes the next ‘Brilliant’ thing to rave about.
Get a life!
Tinus: Although I’m not a fan of the glad-handing that goes on in these threads, the fact of the matter is that Doug published a solidly good idea — one that a good number of these folks hadn’t had before. And “a-list”? I didn’t know that was even something still talked about… Doug is popular… he’s popular because of who he knows (that soft underbelly of blogdom), but here, right now, he’s popular for _what_ he knows. Is that something really worth your vitriol? Good heavens, man. Get a life!
(Doug… quotes, apostrophes, and double dashes are automatically converted, but why not the real em dash?)
I’ve been doing web design/development for years and know about the items above, but never seem to get around to doing it. If anything, it’s a good reminder that others may end up inheriting your work. Thanks!
Hey Silus (and others),
I know Doug knows what he talks about. He must be 10 times better than I am at this stuff, and he should get a lot of credit for what does and knows. But why people call this particular thing ‘brilliant’ is beyond me. Hey, it is just a _good_ idea, so lets just call it that, and reserve the word ‘brilliant’ for the truly amazing things.
By the way, I apologize for saying ‘Get a life’, that really was a stupid thing to say.
Tinus
It’s all good.
The irony, Tinus, is that you hit on a good point (whether you meant to or not, I have no idea): namely, that glad-handing and trolling are of a kind. They both degrade the signal to noise ratio. Glad-handing is just easier to swallow.
: )
(Hey Doug: my e-mail, which is saved to a cookie, gets munged every time I try to post. Grr.)
I am Dutch (maybe that explains something…) and didn’t have a clue what the word gladhanding meant, but I looked it up and yes, that is exactly what I meant.
But hey, all I am doing right now is adding more noise to this thread, so I’ll add some more signal..
@#22
It might be a good idea to run the css file through a php script that rips out all comments before sending it to the browser.
Tinus: regarding the PHP script… how would that affect source surfing? Would folks still be able to see a commented version of the style sheet from the web?
Also: isn’t glad-handing a great term?
: )
Silus: I think with PHP you might run into a cacheing problem, but I don’t know for sure. Somebody might have tried it, I didn’t.
For me personally I don’t care if the PHP script returns some obfuscated code, there’s nothing special about my CSS file. My comments are there because I (the developer) need them, my visitors don’t. For Patrick this might be a good idea, combining handy comments with small file sizes.
Speaking of glad-handing.. I’d really appreciate it if Douglas continues to add ‘public’ comments in his code. He has, after all, some _good_ tips now and then. :-)
I use my CMS to sort out CSS hierarchies http://www.poociboo.de/media/user/media_307.jpg
Especially for stuff like “#navi ul li a.sel:hover” it’s really handy, since you find everything in the #navi node.
My 2cents.
Extending this idea, I actually break each of my groups into separate CSS files. I then have a master file which uses @imports to bring in each of the ‘modules’.
Before you all scream….. yes, this slows down page load significantly because if I have 7 or 8 ‘modules’ they can’t all be loaded asynchronously.
The solution? Because I work in ASP.NET I have the power of the pipeline at my control. So, I have made a HTTP Module that inlines any linked stylesheets. From the user/broswers point-of-view, it’s just one large file. From my point-of-view it’s a series of completely separate CSS files.
I’m sure you could acheive this on other platforms – I just haven’t tried.
Just out of curiousity is there anything like Javadoc for CSS?
Doug,
Using TextMate on my mac, I can do this:
-flag
and then hit
tab
and I get/* Flag
------------------------ */
Where “Flag” is selected so i can just start typing my flag name, it’s a huge time saver.
Just a quick addition:
I needed to update my snippet :-D
now it does the following:
/* =Flag
------------------------ */
but still only selects the flag part for overwriting.
Casey — good idea. One I also use in BBEdit by way of a Glossary Item. Type my short label then hit a keyboard shortcut I’ve assigned to the Glossary item, and BBEdit instantly converts it into a commented header.
I’ve been doing this in code files since college. It’s a great tip.
I sometimes tag my CSS with
/****====****/
between sections. It’s easy to see visually, and you can do this to jump between sections in most text editing environments.
Ctrl-F, search for ====
Click “OK” or cancel or whatever when you get to your section.
F3 now magically jumps to the next section. It’s a lot easier to press F3 a bunch of times than the whole Edit, Find business.
Also, UltraEdit has a CSS wordlist that does a nifty thing. In a sidebar pane, you can show all of the selectors, and double-clicking jumps to the rule.
An even better method would be to get rid of TYPING VISUAL PROPERTIES in CSS all together. It should be a visual design process and we shouldn’t have to type visual properties in a file at all. If your using CSS to “design” the visual aesthetic of your site, its a- type this, save it, and refresh the browser to see the results. What year is it again? Controlling the visual presentation of a design by typing text is primitive.
Wow.. Like many of you I also use CSSEdit and skEdit. CSS Edit especially with it’s live preview is very very handy with large CSS files. Sectioning your CSS is also a good thing to do so thanks for the great tips!
here are my rules:
– use the cascade to avoid duplicating css rules, eg. declare the base font in the body selector
– classes can often be avoided by using contextual selectors, eg. “div#content p” instead of “p.content”, this makes your HTML more efficient
– use headings in the stylesheet
– if your stylesheet is still too long to be manageable due to the complexity of your site, separate into different stylesheets, eg. main.css, nav.css, lists.css, and use @import to bring them into the main stylesheet.
Hi all,
I’ve adopted a node-tree approach to writing out my CSS.
Chances are, you’re looking at well-indented and easy to read HTML, why not mimic this structure in your CSS?
e.g.:
<div class="content">
<p>Lorem <b>Ipsum</b></p>
</div>
could easily be represented in the CSS as:
div.content {/* rules for this node go here */}
div.content p {/* rules for this node go here */}
div.content p b {/* rules for this node go here */}
I create two disctinct sections, a general section and this node-tree section using indenting. It means you need to keep all your CSS properties in one line so you can truly see the hierarchy of markup nodes, but I’d rather sideways-scroll to get to a property than vertically scroll and potentially not see the node hierarchy.
I reset the indenting in the CSS for important sections such as the “Event Zone” and use lines of comments to break these sections out.
Thoughts?
Shaun
= Another option for organizing your CSS might be to
= group rules by objects. So all your headers are together,
= all your lists are together, all your different image
= classes are together…
This seems like a good idea, from an organizational standpoint, but at least in my case, it works against me.
I have noticed over the years that I use a sort of vertical, peripheral look-ahead when skimming style sheets, and a selector like
html>body #content div.subcontent:first-child .entry-header h3 {
}
completely throws me for a loop.
Can anyone recommend a good resource which descibes how to begin laying out a stylesheet for a site redesign?
I’m used to programming and html, but I can’t seem to get my head around the concepts required to design a site layout based on CSS so that it’s easy to change the look and feel by modifying the style sheet. Do people usually start with a complete style sheet and then tweak it? Does the stylesheet get designed before the HTML or do you build the stylesheet as you code the HTML and see what you need?
It would seem that to really allow the stylesheet to drive the look and feel, that the stylesheet would come first and be in a clearly understood structure, Then the HTML coded to use the appropriate ids/tags?
My site is pretty dated and I want to snaz it up and simplify the HTML :D
Lost in CSS – San Francisco
Can anyone recommend a good resource which descibes how to begin laying out a stylesheet for a site redesign?
I would love to help out, L.i.CSS, but I am not sure what you need. I have always started with the premise that markup comes first, and thus informs the style, while at the same time giving it boundaries. If you are looking to redesign your website from the ground up, you should probably start by determining what content on your site needs to stay, what parts will change, and then begin to lay out the new structure, using semantically correct and valid markup. This last bit is key. If you get stuck at this point, and you need a creative nudge, do what every other designer does upon seeing something they like:
View Page Source. ;)
Here are a couple of resources I would recommend:
Listamatic to sort out your navigation — I recall my own headslapping epiphany when I realized how easily I could do away with the tangle of divs spans and anchors I called a navbar.
Dave Shea’s CSS Crib Sheet is a good checklist of fundamentals.
Good luck, and remember: Validate, Validate, Validate! :)
Ah, so simple. Thank you for that. I’ve had this problem for ages, and never found a good way to resolve it.
— Andy
If i have a large css file i just put all the rules in one line! This is what works best for me.
So in stead of this:
#nav {
float:left;
width:182px;
border-top:1px solid #911;
}
i do this:
#nav {float:left;width:182px;border-top:1px solid #911;}
This reduces the number of lines dramaticly.And al your id’s and classes are nicely directly above/under each other…
Topstyle pro has a handy style sweeper which does it automaticly, if you want to do it with it existing css files.
And for the ordering i try to use the ordering of the html file ;-)
Since I started learning CSS based upon a Blogger template of yours (thanks!), I’ve continued to use your commenting/structure/organizational method, which I not only like but also thought was flagged already. Searching for “/* rde” isn’t good enough for you?! ;)
Nice technique, Doug.
You can also do a similar thing with an undocumented feature in Topstyle, called bookmarks.
Very Very Good technique
Great Tip!, I do use flags in the CSS files I do, yet I never organized them, I have to try that! :)
Note that if you use an embedded style sheet, the multiple hyphens will prevent the page from validating as XHTML.
This is something to consider even if you use external stylesheets, you might end up, for various reasons, embedding the external stylesheet, manually or through a script.
Not that I think validating is the key issue, but just so you know.
@Miki: Note that if you use an embedded style sheet, the multiple hyphens will prevent the page from validating as XHTML.
I don’t think this is true. The dashes should not prevent any (X)HTML docuement from validating. To ensure this, I created a quick example to test.
No errors.
I group elements in sets as well, but I never put generic elements halfway across the document. That is asking for trouble. To go with the cascading nature of CSS instead of against it, one should start with generic elements and work down to more specific instances of elements.
Oh come on guys, it’s a nice thing, but is this really new?
The dashes won’t prevent validation, but internal stylesheets that contain double dashes should be wrapped in CDATA sections in XHTML documents sent as application/xhtml+xml. More info here: Properly Using CSS and JavaScript in XHTML Documents and The perils of using XHTML properly.
This really helpfull for me, it’s more easy to understood by me ;)
Thanks
This is a great tip. Glad I found it. Keep them coming!
– Jared Stenquist
This is great, but if the file you are working on didn’t follow this standard and you don’t feel like scrolling…the DOM Inspector is godsent.
I use Homesite for most of my authoring and I find this trick handy. I label blocks of CSS like this:
/* <navigation> */
…css goes here…
/* </navigation> */
Homesite treats the comments as tags and I can use ctrl+m to quickly jump to the bottom of a category to add new styles.
BTW: Does anyone know if there’s a comparable feature in BBEdit — a keyword shortcut to jump to a closing tag? It’s one of those handy shortcuts I’ve gotten really used to and miss when using BBEdit.
-Justin