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!

Raoulito
  • 361
  • 2
  • 11

2 Answers2

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>
Community
  • 1
  • 1
Banana
  • 7,424
  • 3
  • 22
  • 43
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) );
adeneo
  • 312,895
  • 29
  • 395
  • 388
  • 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 Apr 06 '15 at 15:12
  • `.appendTo($('#div_B').parent())` – Raoulito Apr 06 '15 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 Apr 06 '15 at 16:43