CSS Grouping Script

This is a guest post by Robin Vermeij.

On Idlesoft I had a problem some time ago. I wanted to integrate the forums into the theme, however this messed up the full CSS. That is why I made this script, using ruby. It places all of your styles in a group (like #forum). There are only 2 minor problems with it:

  1. You will need to manually modify definitions like body after the script has ran
  2. It messes up the layout of the CSS file, I advise running a beautifier to it afterward

The code:

1
2
3
4
5
6
7
8
9
10
group = "#forum"
css.gsub!(/\}.*?\{/m) { |match|
    if /,/ =~ match
        match.gsub!(/\s*([^\/,}{]+?)\s*,\s*/, "#{group} #{'\1'}, ")
        match.gsub!(/\s*,\s*([^\/,}{]+?)\s*\{/, ", #{group} #{'\1'}{")
    else
        match.gsub!(/\s*([^\/,}{]+)\s*\{/, "#{group} #{'\1'} {")
    end
    match
}

Example:

1
2
3
4
5
6
7
8
/* Before */
#format-buttons {
    margin: 15px 0 2px 0;
}

#format-buttons input, #format-buttons select {
    vertical-align: middle;
}
1
2
3
4
5
6
/* After */
#forum #format-buttons  {
    margin: 15px 0 2px 0;
}#forum #format-buttons input, #forum #format-buttons select{
    vertical-align: middle;
}

Leave a Comment