• Stars
    star
    206
  • Rank 183,540 (Top 4 %)
  • Language
    JavaScript
  • Created over 11 years ago
  • Updated about 9 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

[unsupported] A CSS compressor that shows no mercy

css-condense

Compresses CSS, and isn't conservative about it.

Status

Installation

Install NodeJS, and:

$ npm install -g css-condense

Usage

$ cssc file.css > file.min.css

Or via NodeJS:

require('css-condense').compress("div {color: red}")

npm version

What it does

Well, it does a lot of things. The most common of which is:

Whitespace removal

It strips whitespaces. Yeah, well, every CSS compressor out there does that, right?

div {
  color: red;
  width: 100%;
}

Becomes:

div{color:red;width:100%}

Identifier compression

Some identifiers, like pixel values or colors, can be trimmed to save on space.

div { color: #ff0000; }
span { margin: 1px !important; }
h1 { background: none; }
a { padding: 0.30em; }
p { font-family: "Arial Black", sans-serif; }
abbr { background: url("tile.jpg"); }

Can be: (newlines added for readability)

div{color:#f00}                           /* Collapsing 6-digit hex colors to 3 */
span{margin:1px!important}                /* Strip space before !important */
h1{background:0}                          /* Change border/background/outline 'none' to '0' */
a{padding:.3em}                           /* Removing trailing zeroes from numbers */
p{font-family: Arial Black,sans-serif}    /* Font family unquoting */
abbr{background:url(tile.jpg)}            /* URL unquoting */

More compressions

ul { padding: 30px 30px 30px 30px; }
li { margin: 0 auto 0 auto; }
.zero { outline: 0px; }
a + .b { color: blue; }
.color { background: rgb(51,51,51); }

Output:

ul{padding:30px}                          /* Collapsing border/padding values */
li{margin:0 auto}                         /* Same as above */,
.zero{outline:0}                          /* Removing units from zeros */
a+.b{color:blue}                          /* Collapse + and > in selectors */
.color{background:#333}                   /* Converting rgb() values to hex */

Keyframe compressions

css-condense will trim out any unneeded vendor prefixes from keyframes.

@-moz-keyframes twist {
  0% {
    -webkit-transform: rotate(30deg);
    -moz-transform: rotate(30deg);
    -o-transform: rotate(30deg);
  }
  100% {
    -webkit-transform: rotate(0);
    -moz-transform: rotate(0);
    -o-transform: rotate(0);
  }
}

Output:

@-moz-keyframes twist{
0%{-moz-transform:rotate(30deg)}
100%{-moz-transform:rotate(0)}
}

Selector/declaration sorting

Each rule has its selectors and declarations sorted. This may not seem like it will net any effect, but (1) it increases the likelihood that consecutive properties will be gzipped, and (2) it will help consolidation (more on that later).

div, a { z-index: 10; background: green; }

becomes:

a,div{background:green;z-index:10}

The dangerous things it does

But that's not all! Here's where things get exciting! (Don't worry, you can turn these off with the --safe flag.)

Consolidation via selectors

Rules with same selectors can be consolidated.

div { color: blue; }
div { cursor: pointer; }

Can be consolidated into:

div{color:blue;cursor:pointer}

Consolidation via definitions

Rules with same definitions will be consolidated too. Great if you use mixins in your favorite CSS preprocessor mercilessly. (Those clearfixes will totally add up like crazy)

div { color: blue; }
p { color: blue; }

Becomes:

div,p{color:blue}

Media query consolidation

Rules with the same media query will be merged into one. Say:

@media screen and (min-width: 780px) {
  div { width: 100%; }
}
@media screen and (min-width: 780px) {
  p { width: 50%; }
}

Becomes:

@media screen and (min-width:780px){div{width:100%}p{width:50%}}

Command line usage

$ cssc --help

  Usage: cssc [<sourcefile ...>] [options]

  Options:

    -h, --help                         output usage information
    -V, --version                      output the version number
    --no-consolidate-via-declarations  Don't consolidate rules via declarations
    --no-consolidate-via-selectors     Don't consolidate rules via selectors
    --no-consolidate-media-queries     Don't consolidate media queries together
    --no-sort-selectors                Don't sort selectors in a rule
    --no-sort-declarations             Don't sort declarations in a rule
    --no-compress                      Don't strip whitespaces from output
    --no-sort                          Turn off sorting
    --line-breaks                      Add linebreaks
    -S, --safe                         Don't do unsafe operations

  The --no-sort switch turns off all sorting (ie, it implies --no-sort-*).
  The --safe switch turns off all consolidation behavior (ie, it implies --no-consolidate-*).

  If a <sourcefile> is not specified, input from stdin is read instead.
  Examples:

    $ cssc style.css > style.min.css
    $ cat style.css | cssc > style.min.css

Programatic usage

You can use the css-condense NodeJS package, or you can use dist/css-condense.js for the browser.

NodeJS:

var cssc = require('css-condense');
var str = "div { color: blue; }";

cssc.compress(str);
cssc.compress(str, {
  sortSelectors: false,
  lineBreaks: true
});

Or with css-condense.js:

CssCondense.compress(str);

But you'll risk breaking things!

Well, yes. You want a safe approach? Use --safe or go with YUI Compressor.

But hey, css-condense tries its best to make assumptions to ensure that no breakage (or at least minimal breakage) will happen.

For instance, consolidating media queries can go wrong in this case:

/* Restrict height on phones */
@media screen and (max-width: 480px) {
  .box { max-height: 10px; } /* [1] */
}
.box {
  padding: 20px; /* [2] */
}
/* Small screens = less spacing */
@media screen and (max-width: 480px) {
  .box { padding: 10px; } /* [3] */
}
div { color: blue; }

The two media queries have the same query, and will be subject to consolidation. However, if the [3] is to be consolidated into [1], you will not get the effect you want.

/* Bad :( */
@media screen and (max-width:480px){.box{max-height:10px;padding:10px}}
.box{padding:20px}
div{color:blue}

.box's padding is supposed to be overridden to 10px, which in this case, doesn't happen anymore.

css-condense then makes the assumption is that media queries are usually used to override "normal" rules. The effect is that in cases like these, consolidated rels are placed at its last appearance:

/* Good -- css-condense does things this way! */
.box{padding:20px}
@media screen and (max-width:480px){.box{max-height:10px;padding:10px}}
div{color:blue}

However, it indeed isn't perfectly safe: if you have a max-height rule on the regular .box, you're gonna have a bad time.

What about with CSS rules?

css-condense also goes by the assumption that most people put their least specific things on top (like resets).

body, div, h1, p { margin: 0; padding: 0; }
.listing h1 { padding: 10px; }
.item h1 { margin: 0; padding: 0; }

Now if .item is inside .listing, all of these rules affect .listing h1. The final effect is that the h1 will have a padding of 0.

If the consolidation puts things on top, h1 will get a padding of 10px. Not good.

/* Bad :( */
body,div,h1,p,.item h1 { margin: 0; padding: 0; }
.listing h1 { padding: 10px; }

...which is why css-condense assumes that the more specific things are usually at the bottom. This then compresses nicely to:

/* Good -- css-condense knows what's good for you. */
.listing h1 { padding: 10px; }
body,div,h1,p,.item h1 { margin: 0; padding: 0; }

...giving your H1 the right padding: 0.

How's the real-world performance?

I ran it through some real-world CSS files that have already been compressed, and usually get around 5% to 25% more compression out of it.

Example: https://gist.github.com/3583505

But gzip will compress that for you anyway!

Yes, but css-condense will also reduce the number of rules (usually around 10% to 40% less rules!), which can hypothetically make page rendering faster :)

Acknowledgements

Special thanks to TJ Holowaychuk for css-parse which this project uses to parse CSS, and css-stringify which is used to build the final output.

Thanks

css-condense © 2012+, Rico Sta. Cruz. Released under the MIT License.
Authored and maintained by Rico Sta. Cruz with help from contributors.

ricostacruz.com  ·  GitHub @rstacruz  ·  Twitter @rstacruz

More Repositories

1

nprogress

For slim progress bars like on YouTube, Medium, etc
JavaScript
25,552
star
2

cheatsheets

My cheatsheets
SCSS
13,391
star
3

jquery.transit

Super-smooth CSS3 transformations and transitions for jQuery
JavaScript
7,328
star
4

rscss

Reasonable System for CSS Stylesheet Structure
3,894
star
5

flatdoc

Build sites fast from Markdown
CSS
2,679
star
6

webpack-tricks

Tips and tricks in using Webpack
2,359
star
7

sparkup

A parser for a condensed HTML format
Python
1,562
star
8

backbone-patterns

Common Backbone.js usage patterns.
760
star
9

remount

Mount React components to the DOM using custom elements
JavaScript
675
star
10

sinatra-assetpack

Package your assets transparently in Sinatra.
CSS
542
star
11

jsdom-global

Enable DOM in Node.js
JavaScript
472
star
12

hicat

Command-line syntax highlighter
JavaScript
405
star
13

kingraph

Plots family trees using JavaScript and Graphviz
JavaScript
390
star
14

vim-closer

Closes brackets
Vim Script
329
star
15

scour

Traverse objects and arrays with ease
JavaScript
308
star
16

mocha-jsdom

Simple jsdom integration with mocha
JavaScript
254
star
17

swipeshow

The unassuming touch-enabled JavaScript slideshow
JavaScript
191
star
18

rsjs

Reasonable System for JavaScript Structure
181
star
19

vim-coc-settings

My Vim settings for setting it up like an IDE
Vim Script
164
star
20

startup-name-generator

Let's name your silly startup
JavaScript
164
star
21

onmount

Safe, reliable, idempotent and testable behaviors for DOM nodes
JavaScript
156
star
22

psdinfo

Inspect PSD files from the command line
JavaScript
147
star
23

vim-hyperstyle

Write CSS faster
Python
144
star
24

vim-from-scratch

Rico's guide for setting up Vim
144
star
25

js2coffee.py

JS to CoffeeScript compiler. [DEPRECATED]
Python
127
star
26

firefox-stealthfox

Firefox customization for stealth toolbars
CSS
122
star
27

mocha-clean

Clean up mocha stack traces
JavaScript
107
star
28

jquery-stuff

A collection of small jQuery trinkets
JavaScript
96
star
29

npm-pipeline-rails

Use npm as part of your Rails asset pipeline
Ruby
95
star
30

navstack

Manages multiple screens with mobile-friendly transitions
JavaScript
94
star
31

bootstrap-practices

List of practices when using Bootstrap in projects
90
star
32

details-polyfill

Polyfill for the HTML5 <details> element, no dependencies
JavaScript
89
star
33

dom101

DOM manipulation utilities
JavaScript
82
star
34

unorphan

Removes text orphans
JavaScript
81
star
35

expug

Pug templates for Elixir
Elixir
80
star
36

stylelint-rscss

Validate CSS with RSCSS conventions
JavaScript
74
star
37

feh-blur-wallpaper

Blur your desktop wallpaper when windows are open
Shell
73
star
38

pomo.js

Command-line timer, great for Pomodoros
JavaScript
73
star
39

sinatra-backbone

Neat Backbone.js integration with Sinatra.
Ruby
72
star
40

flowloop

A Pomodoro-like timer for hyper-productivity
JavaScript
71
star
41

vimfiles

My VIM config files.
Lua
63
star
42

bookmarks

My bookmarks
63
star
43

my_qmk_keymaps

Keymaps for keyboards
C
59
star
44

typish

Typewriter simulator
JavaScript
58
star
45

iconfonts

Fine-tuned icon fonts integration for Sass, Less and Stylus
CSS
54
star
46

pre.js

Efficient, resilient resource preloader for JS/CSS
JavaScript
54
star
47

tape-watch

Rerun tape tests when files change
JavaScript
53
star
48

tinkerbin

Tinkerbin.com
JavaScript
52
star
49

vim-fastunite

Search for files fast
Vim Script
48
star
50

collaborative-etiquette

A manifesto for happy Open Source projects
46
star
51

decca

Render interfaces using pure functions and virtual DOM
JavaScript
45
star
52

vim-opinion

My opinionated vim defaults
Vim Script
44
star
53

modern-development

Using agile methods to build quality web applications
CSS
43
star
54

til-2013

Old version of http://ricostacruz.com/til (2015-2018)
CSS
42
star
55

ion

[deprecated] Ruby/Redis search engine.
Ruby
41
star
56

timetip

Deliciously-minimal time tracker for the command-line
JavaScript
40
star
57

vim-xtract

Extract the selection into a new file
Vim Script
39
star
58

bump-cli

Command-line version incrementer
JavaScript
39
star
59

halla

Native Slack wrapper app without the bloat
JavaScript
38
star
60

newsreader-sample-layout

CSS
36
star
61

ento

Simple, stateful, observable objects in JavaScript
JavaScript
36
star
62

cron-scheduler

Runs jobs in periodic intervals
JavaScript
35
star
63

promise-conditional

Use if-then-else in promise chains
JavaScript
34
star
64

ractive-touch

Touch events for Ractive
JavaScript
33
star
65

git-update-ghpages

Simple tool to update GitHub pages
Shell
33
star
66

jquery.unorphan

[deprecated] Obliterate text orphans.
JavaScript
33
star
67

greader

[UNSUPPORTED] Google Reader API client for Ruby
Ruby
32
star
68

penpad

Design and document web UI components
TypeScript
32
star
69

typecat

TypeScript
31
star
70

react-meta-elements

Sets document title and meta tags using React elements or hooks
TypeScript
31
star
71

vim-ultisnips-css

[deprecated] Write CSS in VIM faster.
Ruby
31
star
72

tape-plus

Nested tape tests with before/after, async, and promise support
JavaScript
30
star
73

taskpaper.js

Taskpaper parser in JavaScript
JavaScript
28
star
74

frontend-starter-kit

Rico's opinionated Metalsmith frontend kit
JavaScript
28
star
75

homebrew-backup

Back up your Homebrew profile
Shell
28
star
76

fishfiles

my fish-shell config files
Shell
28
star
77

passwordgen.js

Password generator for the command line
JavaScript
28
star
78

reacco

Generate documentation from README files.
Ruby
26
star
79

ghub

Open this project in github
Shell
26
star
80

sass_icon_fonts

Sass 3.2 integration with modern icon fonts.
CSS
26
star
81

lidoc

[Deprecated] Literate-programming style documentation tool.
CoffeeScript
24
star
82

rspec-repeat

Repeats an RSpec example until it succeeds.
Ruby
24
star
83

lofi

VHS music machine from the 80's
JavaScript
24
star
84

sinatra-template

Ruby
24
star
85

fish-asdf

Fish shell integrations for asdf version manager
Shell
24
star
86

wiki

Stuff
23
star
87

arch-installer

Install UI for Arch Linux
Shell
22
star
88

slack-emoji-magic

Magic: the Gathering emojis
Makefile
21
star
89

node-hledger

Node.js API for hledger
JavaScript
21
star
90

vimbower

Use bower, git and pathogen to manage your vim setup
21
star
91

ractive-promise-alt

Adaptor for Ractive.js to support promises
JavaScript
21
star
92

til-2020

Today I learned blog of @rstacruz
TypeScript
21
star
93

webpack-starter-kit

Baseline configuration for Webpack
JavaScript
21
star
94

phoenix_expug

Expug integration for Phoenix
JavaScript
20
star
95

cssutils

Collection of Sass utility mixins and other goodies.
CSS
20
star
96

responsive-modular-scale.css

Responsive typography using CSS variables
20
star
97

cdnjs-command

Command line helper for cdnjs.com
Ruby
20
star
98

curlformat

CLI utility to clean up your "Copy as cURL" strings
JavaScript
19
star
99

ractive-loader

ractive template loader for webpack
JavaScript
19
star
100

ajaxapi

Minimal AJAX library for APIs. Supports promises
JavaScript
18
star