Is it possible to do mathematics inside CSS?

前端 未结 5 1047
孤独总比滥情好
孤独总比滥情好 2020-12-01 01:36

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 .simp

相关标签:
5条回答
  • 2020-12-01 01:53

    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.

    0 讨论(0)
  • 2020-12-01 02:09

    You can do maths in CSS e.g.:

    height: calc(100% - 20%);

    CSS will also handle the different units, so this works too:

    height: calc(100% - 20px);

    Additionally, min(), max() and clamp() have also been added allowing for calculations like this:

    height: min(calc(100% - 20px), 50%);

    1. min(): gets the minimum value;
    2. max(): gets the maximum value; and
    3. clamp(): limits a value by providing an upper and lower bound.
    0 讨论(0)
  • 2020-12-01 02:13

    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/

    0 讨论(0)
  • 2020-12-01 02:15

    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.

    0 讨论(0)
  • 2020-12-01 02:18
    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).

    0 讨论(0)
提交回复
热议问题