1

I want to do fallback for calc() in my css with jquery

CSS:

width: calc(100% - 90px);

so I wrote below code but seem the 2nd css() doesn't run. I think something is wrong but I've no clue.

jQuery:

var paxWidth = '-' + ($('.pax').width() + 10) + 'px';
console.log(paxWidth); // this return -90px
$('.datetime,.placeholder').css('width','100%').css('width', paxWidth);
Mardzis
  • 760
  • 1
  • 8
  • 21
James Lemon
  • 426
  • 5
  • 17

1 Answers1

1

When you set width with css method twice in a row the second simply overwrites previous. In your case to mimic 100% - 90px width you need to actually calculate this difference in px and apply the result.

Now, percentage width 100% is calculated relatively to a parent container, it means that for 100% value you need to do something like this:

var paxWidth = $('.pax').width() + 10;
$('.datetime, .placeholder').css('width', function() {
    var parentWidth = $(this).parent().width();
    return parentWidth - paxWidth;
});

Demo: http://jsfiddle.net/02cxqpzq/

UPD. Looking at duplicated answer, I can confirm that my above solution makes little sense since it can be as simple as

$('.datetime, .placeholder').css('width', '100%').css('width', '-=90px');

Demo: http://jsfiddle.net/02cxqpzq/1/

dfsq
  • 191,768
  • 25
  • 236
  • 258
  • why does this guy answer got many upvotes : http://stackoverflow.com/questions/11117216/css-width-calc100-100px-alternative-using-jquery ?? – James Lemon Mar 03 '15 at 07:45
  • Interesting, didn't know about it! I think this is a right way to do it. Did you try it? – dfsq Mar 03 '15 at 08:05