2

I want to apply the width of #div_A minus 3 em to #div_B.

$("#div_B").width($("#div_A").width() - 3);

I did not find anything that explained how to specify only 3 in em.

Thanks!

1
  • first of all, you are assigning the width of div_b to div_a, not the other way around.
    – Banana
    Commented Apr 4, 2015 at 17:19

2 Answers 2

3

Here is how to convert pixels to em using jquery.

you could however, take advantage of the css calc() function in combination with jquery to make it much much shorter:

$(function() {
  $("#div_B").css({
    "width": "calc(" + $("#div_A").width() + "px - 3em)"
  });
});
div{
    display:block;
    height:100px;
    background:blue;
}
#div_A{
    width:100px;
    background:red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="div_A"></div>
<div id="div_B"></div>

1
  • Thanks, I did not know about this calc function. Works great!
    – Raoulito
    Commented Apr 4, 2015 at 17:35
1

For full browser support you have to figure out how much 3em is in pixels.

You'd do that by using an element set to 3em and getting the pixel value from it

var div = $('<div />', {
    css : {
        position : 'relative',
        width    : '3em',
        height   : '1em'
    }
}).appendTo('body');

var w = div.width(); // width of 3em in pixels

div.remove();

$("#div_B").width( $("#div_A").width() - w );

As em is the same as the currently used font-size, one could also do

var em = (+$("#div_A").css('font-size').replace(/\D/g,''));
$("#div_B").width( $("#div_A").width() - (em * 3) );
3
  • That's a good solution too, thanks. In my case there's a limit to it as the em size of an element is relative to the em size of its parent element. So I would have to make the var div I use to calculate 3em appendTo the element in which #div_B is located.
    – Raoulito
    Commented Apr 6, 2015 at 15:12
  • .appendTo($('#div_B').parent())
    – Raoulito
    Commented Apr 6, 2015 at 15:21
  • Actually, em would be relative to the font-size, so you really just need to get the font-size and divide by 3
    – adeneo
    Commented Apr 6, 2015 at 16:43

Your Answer

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

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