Home » Html » Is it possible to do mathematics inside CSS?

Is it possible to do mathematics inside CSS?

Posted by: admin November 29, 2017 Leave a comment

Questions:

I have jquery accorion id #accordion and some of the content inside header class name .simpleColor. Now I want to give a calculated margin to .simpleColor. In pseudo…it looks something like this,

.simpleClass {
    margin-left: ((#accordion.width/2) - (.simpleColor.width/2));
}

I am open to use any other technology such as javascript to achieve this if it is possible.

Answers:

There’s a CSS function called calc that is starting to get pretty good support. The syntax works as followed:

width: calc(50% - 100px);

(Note that the whitespace around the operators is significant)

This allows true dynamic computational support in CSS. With a preprocessor, you can only combine static lengths with static lengths, and relative lengths with relative ones.

Calc is supported since Chrome 19, Firefox 4, and IE9. The feature isn’t quite widely supported enough to use it widely, but it will be not too far into the future and it’s something to remember and look forward to.

Questions:
Answers:

It is not possible to do mathematic operations inside CSS natively. You could use JavaScript to change CSS properties on page load, but this is a pain and must be done every page load making your page slow.

You’ll need to use a CSS preprocessor like LESS, Stylus, or SASS.

The bonus to using either of these languages is that you can generate actual CSS stylesheets from them. You also get benefits like functions, mixins, variable, and more.

Questions:
Answers:
jQuery('.simpleClass').css('margin-left', (jQuery('#accordian').width() / 2) - (jQuery('.simpleColor').width() / 2) + 'px');

Should do what you are wanting. But you need to do something like this in javascript, you can’t do it in pure CSS unless the widths for #accordian and .simpleColor are known in advance (and thus calculated in advance).

Questions:
Answers:

If you’re open to using other technology, try using less: http://lesscss.org/

Questions:
Answers:

I believe the CSS should be pure style definition. I dont like to mix some calculations with that. I would do that in my javascript

var accWidth=parseInt($("#accordion").css("width").replace("px",""));
var simpWidth=parseInt($(".simpleColor").css("width").replace("px",""));
var marginLeft=((accWidth/2)-(simpWidth/2));       
$(".simpleClass").css("margin-left",marginLeft);

Working sample http://jsfiddle.net/mzTRw/19/

Questions:
Answers:

See this Example.. He has used much math in css.

http://codepen.io/schoenwaldnils/pen/DLiyr