9

How can I increase the width of an element by 10rem using jquery. Issue is Jquery always return width/height in pixels and we want to update the height/width in some other units.

Example on: JS Bin

var $c = $('#container');
console.log($c.width());

var c = document.getElementById('container');

// Q1. Why is it different from above one. This is 324 while earlier it was 320. See the output.
console.log(c.clientWidth);

// Q2. How to update the code to increase the width by 10rem.
$c.css({width: $c.width() + 10}); //It adds 10 pixels here.

console.log($c.width());

My questions are comments in the code.

2
  • 2
    Agree with your question but I think rem unit is for Fonts only according to W3C standars see: w3.org/TR/css3-values Apr 18, 2013 at 17:06
  • 1
    Yeah fine but these days em/rem units are quite used in apps because this allows page content fit according to the device size..As the font size changes everything else changes accordingly.. Apr 18, 2013 at 17:11

2 Answers 2

15

I suppose that taking the font-size of the html element will give you the rem, using a function, you'll be able to retrieve it even if it changes:

   // This Function will always return the initial font-size of the html element 
   var rem = function rem() {
        var html = document.getElementsByTagName('html')[0];

        return function () {
            return parseInt(window.getComputedStyle(html)['fontSize']);
        }
    }();

// This function will convert pixel to rem
    function toRem(length) {
        return (parseInt(length) / rem());
    }

example: http://jsfiddle.net/4NkSu/1/

1
  • 1
    Nicely done @xpy. I thought there should exist some elegant/simple solution to this. Yours one is nice too :) Apr 19, 2013 at 3:33
8

Decided to post an updated answer using jquery. You can call the function without a parameter to get the number of pixels in one rem, or you can pass in a count for rem to get the number of pixels in that many rem. Here's a jsFiddle also: http://jsfiddle.net/drmyersii/mr6eG/

var rem = function (count)
{
    var unit = $('html').css('font-size');

    if (typeof count !== 'undefined' && count > 0)
    {
        return (parseInt(unit) * count);
    }
    else
    {
        return parseInt(unit);
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.