[jquery] css width: calc(100% -100px); alternative using jquery

I'd like to use width: calc(100% -100px); which does the job perfectly for what I need it for, the only problem is its compatibility. At the moment it only works in the latest browsers and not at all in Safari.

Could I make an alternative using jQuery? ie. get the 100% width of an object -100px and then dynamically set the result as the CSS width (so it would be responsive)

This question is related to jquery css

The answer is


Try jQuery animate() method, ex.

$("#divid").animate({'width':perc+'%'});

I think this may be another way

    var width=  $('#elm').width();

    $('#element').css({ 'width': 'calc(100% - ' + width+ 'px)' });

Its not that hard to replicate in javascript :-) , though it will only work for width and height the best but you can expand it as per your expectations :-)

function calcShim(element,property,expression){
    var calculated = 0;
    var freed_expression = expression.replace(/ /gi,'').replace("(","").replace(")","");
    // Remove all the ( ) and spaces 
    // Now find the parts 
    var parts = freed_expression.split(/[\*+-\/]/gi);

    var units = {
        'px':function(quantity){
            var part = 0;
            part = parseFloat(quantity,10);
            return part;
        },
        '%':function(quantity){
            var part = 0,
            parentQuantity = parseFloat(element.parent().css(property));
            part = parentQuantity * ((parseFloat(quantity,10))/100);
            return part;
        } // you can always add more units here.
    }

    for( var i = 0; i < parts.length; i++ ){
        for( var unit in units ){
            if( parts[i].indexOf(unit) != -1 ){
               // replace the expression by calculated part.
               expression = expression.replace(parts[i],units[unit](parts[i]));
               break;
            }
        }
    }
    // And now compute it. though eval is evil but in some cases its a good friend.
    // Though i wish there was math. calc
    element.css(property,eval(expression));
}

If you want to use calc in your CSS file use a polyfill like PolyCalc. Should be light enough to work on mobile browsers (e.g. below iOS 6 and below Android 4.4 phones).


100%-100px is the same

div.thediv {
  width: auto;
  margin-right:100px;
}

With jQuery:

$(window).resize(function(){
  $('.thediv').each(function(){
    $(this).css('width', $(this).parent().width()-100);
  })
});

Similar way is to use jQuery resize plugin