<button>Convert PX to EM</button>
<textarea></textarea>
CSS
textarea {
width: 100%;
height: 500px;
}
JavaScript
var basePxSize = 16;
var decimalPlaces = 3;
////////////////////////////////////////
var findPX = new RegExp('(\\d+)px','g');
//define decimalPlaces + 1, to round it if there are more places
var decPlaces = new RegExp('(\.\\d{' + decimalPlaces + '}\\d).*', '');
var last = new RegExp('(\\d$)', '');
$('button').on('click', function () {
var css = $('textarea').val();
var result;
while ((result = findPX.exec(css)) !== null) {
var px = parseInt(result[1]);
var em = px / basePxSize;
//find decimal places defined in decimalPlaces variable
//if there is more decimal places, round it
result = decPlaces.exec(em);
if (result !== null)
em = round(em, result[1]);
css = css.replace(px + 'px', em + 'em');
}
$('textarea').val(css);
});
function round (base, num) {
var leadingZero = '';
//base 1.2345 num .2345
num = num.toString();
//remove . from num, num 2345
num = num.substring(1, num.length);
//if first char is zero 0234, remember it and substring 0, because Math will ignore it when round
if (num.charAt(0) == 0) {
leadingZero = '0';
num = num.substring(1, num.length);
}
//make last point as decimal places, so Math can round it, num 234.5
num = num.replace(last, '.$1');
//round num 234.5 -> 235
num = Math.round(num);
//take only base value, base 1
base = base.toString().split('.')[0];
//concanate base and rounded decimal, 1 . 235
return base + '.' + leadingZero + num;
}
Please Whitelist JSFiddle in your content blocker.
Help keep JSFiddle free for always by one of two ways:
Whitelist JSFiddle in your content blocker (two clicks)
Go PRO and get access to additional PRO features →
Join the 4+ million users, and keep the JSFiddle dream alive.
Ad-free
All ads in the editor and listing pages are turned completely off.
Use pre-released features
You get to try and use features (like the Palette Color Generator) months before everyone else.
Fiddle collections
Sort and categorize your Fiddles into multiple collections.
Private collections and fiddles
You can make as many Private Fiddles, and Private Collections as you wish!
Console
Debug your Fiddle with a minimal built-in JavaScript console.