script to convert css sheet from px to em

Sy Moen picture Sy Moen · Jan 1, 2011 · Viewed 9.8k times · Source

Anyone know of a script (php, python, perl, bash, whatever) that will convert a stylesheet from px to em?

Like, it would take input of the filename and base font-size (default 16) and convert all px instances to em?

eg:

convertpx2ems --file stylesheet.css --base-font-size 16

would convert this:

button {
    font-size:14px;
    padding:8px 19px 9px;
}

to something like this:

button {
    font-size: .875em;
    padding: .5em 1.188em .563em;
}

...maybe, is there a way to do this with sass?

Answer

neemanjabu picture neemanjabu · Apr 12, 2013

Copy/Paste your css in JSFiddle to convert. code example:

var regFindPX = new RegExp('(\\d+)px','g');
var reg3decPoints = new RegExp('(\.\\d{3}).*', '');

var css = 'css code';
var result;
while ((result = regFindPX.exec(css)) !== null) {
    var px = parseInt(result[1]);
    var em = px / 16;
    em = em.toString().replace(reg3decPoints, '$1');
    css = css.replace(px + 'px', em + 'em'); 

}