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!
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!
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>
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) );
var div
I use to calculate 3em appendTo the element in which #div_B
is located.
em
would be relative to the font-size, so you really just need to get the font-size and divide by 3