CSS¶
minify_css makes a stylesheet smaller. It removes what the browser does
not need, such as comments and spaces, and the page still looks the same.
See Minifier if the word is new to you.
import korpress
korpress.minify_css('a { color : red ; }')
# 'a{color:red}'
The spaces and the last ; are gone, and the rule means the same.
Before and after¶
import korpress
src = """/* Page styles */
body {
margin : 0px ;
color : #FFFFFF ;
background : url( 'bg.png' ) ;
}
.card > .title ,
.card .sub {
font-size : 0.50em ;
padding : 0.0px ;
}
.empty { }
"""
print(korpress.minify_css(src))
body{margin:0;color:#fff;background:url(bg.png)}.card>.title,.card .sub{font-size:.5em;padding:0}
The input is 190 characters and the output is 97.
The idea¶
minify_css reads a stylesheet and writes it again with everything the
browser does not need: comments, spaces, line breaks, the last ; of a
block, empty rules. It also writes some values in a shorter form, such as
0.50em as .5em.
It does not merge rules, reorder them or rename anything. So the result is smaller, but not as small as a tool that rewrites your CSS.
What korpress changes¶
Each row is a real input and the output you get.
| Rule | Before | After |
|---|---|---|
| Remove comments | a /* x */ { color: red /* z */; } |
a{color:red} |
| Remove spaces and line breaks | a { color : red ; } |
a{color:red} |
Remove the last ; of a block |
a{b:c;;;} |
a{b:c} |
| Tighten selectors | a,\n b > c ~ d + e { margin : 0 auto } |
a,b>c~d+e{margin:0 auto} |
| Keep a descendant space | a :hover { x: y } |
a :hover{x:y} |
Tighten :not() and :is() |
a:not( .b , .c ) > d{x:y} |
a:not(.b,.c)>d{x:y} |
| Drop empty rules | a{} b{c:d} @media print{ e{} } |
b{c:d} |
| Tighten at-rules | @media screen and (min-width : 100px) , print { a { b : c } } |
@media screen and (min-width:100px),print{a{b:c}} |
Tighten @import and @charset |
@charset "utf-8" ;\n@import url( a.css ) screen ; |
@charset "utf-8";@import url(a.css) screen; |
| Shorten numbers | a{margin:0.50em -0.5px 1.0px 00.5rem} |
a{margin:.5em -.5px 1px .5rem} |
| Drop the unit of a zero length | a{margin:0px;width:0.0em} |
a{margin:0;width:0} |
| Shorten hex colors | a{color:#FFFFFF;background:#aabbccdd} |
a{color:#fff;background:#abcd} |
| Lowercase hex colors | a{color:#ABCDEF12} |
a{color:#abcdef12} |
Unquote a simple url() |
a{background:url( 'a.png' )} |
a{background:url(a.png)} |
Trim url() content |
a{background:url( data:image/png;base64,AA== )} |
a{background:url(data:image/png;base64,AA==)} |
Close up !important |
a{color:red ! important} |
a{color:red!important} |
| Close up commas in values | a{font-family:a , b ,c} |
a{font-family:a,b,c} |
| Lowercase property names | a{Margin:0} |
a{margin:0} |
| Keep native nesting | a { b : c ; & > d { e : f } &:hover { g : h } } |
a{b:c;&>d{e:f}&:hover{g:h}} |
A few details:
- A zero loses its unit only when it is a length, such as
0px,0emor0.0px. A percentage keeps its sign (0%stays). Times and angles keep their unit:0s,0msand0degstay. - A
url()is unquoted only when the quotes are not needed. A path with a space, or with parentheses, stays quoted. - The comment
/*! ... */is kept. See the option below.
Options¶
minify_css(src, *, keep_important_comments=True) has one option. It is
keyword-only.
keep_important_comments¶
A comment that starts with /*! is a license comment. Many licenses ask you
to keep it in the file you ship, so korpress keeps it.
src = "/*! MIT */ a { b : c } /* x */"
korpress.minify_css(src)
# '/*! MIT */a{b:c}'
korpress.minify_css(src, keep_important_comments=False)
# 'a{b:c}'
An important comment can be anywhere, not only at the top:
korpress.minify_css("a{b:c}/*! mid */d{e:f}")
# 'a{b:c}/*! mid */d{e:f}'
On the command line, --strip-license does the same as
keep_important_comments=False. See Command line.
CSS inside HTML¶
In an HTML page, minify_html runs this minifier on <style> blocks and on
style="" attributes. You switch it off there with minify_css=False. See
HTML. A style="" attribute is a list of declarations, so
korpress minifies it as one, and drops its important comments.
In depth¶
This part is for exact behavior, edge cases and limits.
There is no parser tree: the stylesheet is read once from start to end.
What it never changes¶
Each claim below was run, and the output is shown.
| Left alone | Before | After |
|---|---|---|
| Strings, spaces and all | a::before{content:" a ; }"} |
a::before{content:" a ; }"} |
| The content of an attribute selector | a[ href = "x y" ] > b[c^='d'] { e : f } |
a[ href = "x y" ]>b[c^='d']{e:f} |
A url() that needs its quotes |
a{background:url("a b.png")} |
a{background:url("a b.png")} |
| Quoted values in other functions | a{src:format( 'woff2' )} |
a{src:format('woff2')} |
Spaces around + and - in calc() |
a{width:calc( 100% - (2 * 10px) )} |
a{width:calc(100% - (2 * 10px))} |
A 0px inside calc() |
a{width:calc(0px + 1em)} |
a{width:calc(0px + 1em)} |
A 0px in flex |
a{flex:1 1 0px} |
a{flex:1 1 0px} |
A 0px in a var() fallback |
a{margin:var(--a, 0px)} |
a{margin:var(--a,0px)} |
| Zero times and angles | a{x:0s;y:0ms;z:0deg} |
a{x:0s;y:0ms;z:0deg} |
| Percentages in keyframes | @keyframes k { 50.0% { a : 1 } } |
@keyframes k{50.0%{a:1}} |
| Colors in custom properties | :root{--b : #FFFFFF} |
:root{--b:#FFFFFF} |
| Numbers in custom properties | :root{--a: 0px } |
:root{--a:0px} |
| Old-IE filters | a{filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF)} |
a{filter:progid:DXImageTransform.Microsoft.gradient(startColorstr=#80FFFFFF)} |
| Old hacks | a{*zoom:1;_height:1px;width:100px\9} |
a{*zoom:1;_height:1px;width:100px\9} |
| Escapes in selectors | .\31 23 { a : b } |
.\31 23{a:b} |
| The case of a keyword | a{color:RED} |
a{color:RED} |
Why each one is safe:
- Strings are copied as they are. A
;or}inside a string does not end anything. - Custom properties (
--name) can hold any text, and your JavaScript may read it back. So korpress only removes comments and repeated spaces in them. The value of--babove keeps its upper case, and a--x: ;stays an empty value (--x:). - Zeros in
calc(),flexandvar()fallbacks keep their unit. Inflex: 1 1 0pxa bare0can mean something else, and insidecalc()a bare0cannot be added to a length. - Colors are shortened only when no information is lost.
#123456and#ABCDEF12cannot be written shorter, so they stay (the second one is only lowercased). - Selectors are not reordered or merged. Two rules with the same body stay two rules, because the order of rules can change which one wins.
Errors¶
minify_css never raises KorpressError. A broken stylesheet is not
refused: korpress does its best with what it can read. The result can lose
the part that was never closed. For example, these are real outputs:
| Input | Output |
|---|---|
a{b:c |
a{b:c} |
a{b:"x |
a{b:"x} |
a{ |
an empty string |
/* open |
an empty string |
So minify_css is not a CSS checker. If you need to know that a stylesheet
is valid, check it before you minify it.
A wrong type raises TypeError, as for any Python function:
korpress.minify_css(None)
# TypeError: 'None' is not an instance of 'str'
korpress.minify_css("a{}", True)
# TypeError: minify_css() takes 1 positional arguments but 2 were given
The options are keyword-only, so minify_css(src, False) is refused on
purpose.
Good to know¶
- The input is a
str. To work with files, useminify_fileor the command line. - Minifying the output again gives the same output.
- See Limits and safety for what korpress does not do, and JavaScript for the other minifier.