Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

script to convert css sheet from px to em

Tags:

css

font-size

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?

like image 930
Sy Moen Avatar asked Jan 01 '11 19:01

Sy Moen


People also ask

How do you calculate em in CSS?

An em is equal to the computed font-size of that element's parent. For example, If there is a div element defined with font-size: 16px then for that div and for its children 1em = 16px .

What is 1em to px?

So, by default 1em = 16px, and 2em = 32px.


2 Answers

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'); 

}
like image 76
neemanjabu Avatar answered Sep 17 '22 10:09

neemanjabu


You can't sensibly interchange px and em sizes like that. A px size is an absolute value that will remain the same size regardless of where it is. An em size is relative to the parent element, thus 0.5em is half the size of the parent element. If that doesn't make much sense, consider the following piece of code:

/* CSS */
span { font-size: 0.9em; }

<!-- HTML -->
<span>Testing,
    <span>Testing,
        <span>Testing</span>
    </span>
</span>

In this example you'll find that the word "Testing" gets smaller and smaller because the font size of each span tag is 90% of the one above.

For the body tag, a font-size of 1em is roughly equivalent to 16px, but that is the only time you can sensibly translate one size to another

like image 38
James Long Avatar answered Sep 18 '22 10:09

James Long