height: calc(100%) not working correctly in CSS

后端 未结 7 957
面向向阳花
面向向阳花 2020-12-02 15:09

I have a div that I want to fill the whole height of the body less a set number in pixels. But I can\'t get height: calc(100% - 50px) to work.

The reas

7条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 15:51

    You need to ensure the html and body are set to 100% and also be sure to add vendor prefixes for calc, so -moz-calc, -webkit-calc.

    Following CSS works:

    html,body {
        background: blue;
        height:100%;
        padding:0;
        margin:0;
    }
    header {
        background: red;
        height: 20px;
        width:100%
    }
    h1 {
        font-size:1.2em;
        margin:0;
        padding:0;
        height: 30px;
        font-weight: bold;
        background:yellow
    }
    #theCalcDiv {
        background:green;
        height: -moz-calc(100% - (20px + 30px));
        height: -webkit-calc(100% - (20px + 30px));
        height: calc(100% - (20px + 30px));
        display:block
    }
    

    I also set your margin/padding to 0 on html and body, otherwise there would be a scrollbar when this is added on.

    Here's an updated fiddle

    http://jsfiddle.net/UF3mb/10/

    Browser support is: IE9+, Firefox 16+ and with vendor prefix Firefox 4+, Chrome 19+, Safari 6+

提交回复
热议问题