I was looking at CSS3 calc() and I wondered whether it is possible to subtract a value from the input string with jQuery (or RegEx).
For example:
div {
width: calc(100% - 50px);
}
I want to get the percentual value (100%) and the pixel value (50px) and I need to know what it is followed by (px, em, pt, %).
So basically:
- get a value after
calc(and before a seperator (+,-,*,/) - get a value after the seperator and before
) - note that there could be more values than one!, e.g.
calc(100% - 20px - 0.8em)
EDIT:
Spudley talks of parsing the whole CSS stylesheet, but this might cause overhead. Because this a project for the heck of it, overhead is allowed, so you can go haywire and do whatever you want to accomplish this!
Thanks.
You shouldn’t really do or even need this in a real-life application but since you say this is just for fun; here is the fun part:
Yes you can do it. Loading the CSS file via AJAX calls is not the only way but it may be the only (but inefficient) way to make it really cross-browser.
Even the declaration below won’t make it truly cross-browser sincecalc()function is not supported by all browsers and it’s a CSS3 feature.EDIT: As of 2018,
calcis supported by all modern browsers.You can get the raw CSS code from
document.styleSheetsand their rules. ThecssTextproperty of the rule will give you the full statement. But different browsers may parse the values with acalc()function differently.I’ll go with a more complex example to see how browsers treat the
calc()function:This is how Firefox (v.18) treats it:
And this is how Google Chrome (v.24) treats it:
As shown; FF gets the non-prefixed
calcvalue as it is and Chrome gets the-webkitprefixed value and re-parses it with nested parenthesis (if needed). If you don’t declare it -webkit in Chrome; it will completely ignore the value. So, we should take these into account when we manipulate the calc statement.Now, using the complex example; we will first get the statement inside the calc() function:
Then dissolve the elements of statement into an array:
Finally, process the values and units of the array items to make them programmatically usable (as you wanted):
The final result above includes the value-objects and operators (in order).
Before reading further; note that the code below is not completely tested on all browsers and situations. It does not handle nested parenthesis parsing (like Chrome does) or, values with multiple or combined calc() functions. If you want to test this; I recommend Firefox since it does not parse nested parenthesis OR you can extend the code to enable support for them.
That’s it. As I mentioned, I wouldn’t do this but it’s always good to know if anything is possible.
Note: Since you mentioned making a jQuery plugin (for fun); you don’t really need jQuery for this. And calling functions like
$('div').css('width')will only give you the computed value, not the raw calc statement.