Is it possible to get a negative value with CSS calc()?

Jayx picture Jayx · Aug 8, 2014 · Viewed 39.1k times · Source

Let's say we have a container that is centered in the viewport ...

.centered{margin: 0 auto; width:960px;}

... and inside that container I have another that needs to have a width of 100% the viewport width. I could set the margin to ...

.widest{margin: 0 -480px}

... for example. The thing is that the value won't be -480px, but actually the viewport width (960px) - the .centered width / 2 ... all good and easy with calc(), only I need a result that is a negative value.

.widest{
  margin: 0 calc( (100vw - 960px) / 2 );
}

I've tried subtracting the lot from 0 to get a negative value, but no go.

I don't want to use JS and I only have issues in Webkit - not with the calc() though - my problem is that if I hack it into submission by doing ...

.widest{
  margin: 0 -100%;
}

... my page scrolls horisontally in Chrome/Safari.

Your thoughts?

Answer

FelipeAls picture FelipeAls · Aug 8, 2014

EDIT: A simpler trick than previous ones: calc(0px - something) - with an unit - works while calc(0 - something) doesn't. See Fiddle 3

These "tricks" work:

calc(1px - something - 1px);
calc(-1 * something)
calc(0px - something) /* new */

where 0 - something didn't (at least with your example).

Fiddle 1
Fiddle 2