calc用法

 

<!DOCTYPE html>
<html>
<head>
    <style>
        div {
            width: 400px;
            border: 1px solid;
        }
        p {
            height: 25px;
        }
        #p1 {
            background-color: yellow;
            width: 200px;
            margin-left: calc(100%/2/2);
        }
        #p2 {
            background-color: red;
            width: 100px;
            margin-left: calc(100%/2/2 + 100%/2/2/2);
        }
        #p3 {
            background-color: blue;
            width: 50px;
            margin-left: calc(100%/2/2 + 100%/2/2/2 + 100%/2/2/2/2);
        }
        #p4 {
            background-color: green;
            width: 25px;
            margin-left: calc(100%/2/2 + 100%/2/2/2 + 100%/2/2/2/2 + 100%/2/2/2/2/2);
        }
    </style>
</head>
<body>
    <div>
        <p id="p1"></p>
        <p id="p2"></p>
        <p id="p3"></p>
        <p id="p4"></p>
    </div>
</body>
</html>

其實這是CSS裡面提供的一個方便小功能,如上範例,

calc function 提供了開發者不需實際計算出最終值,

最大好處可以呈現樣式的相對關係讓開發者更容易理解。

calc(expression) 可用加減乘除作運算。

 

另一個 calc 的範例

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <style>
        .div0 {
            width: 200px;
            height: 150px;
            border: 1px solid #000;
        }
        .redbox {
            width: 30px;
            height: 30px;
            background: #c00;
            float: left;
            top: calc(50% - 15px);
            margin-left: calc(50% - 45px);
            position: relative;
        }
        .greenbox {
            width: 30px;
            height: 80px;
            background: #0c0;
            float: left;
            top: calc(50% - 40px);
            position: relative;
        }
        .bluebox {
            width: 30px;
            height: 40px;
            background: #00f;
            float: left;
            top: calc(50% - 20px);
            position: relative;
        }
    </style>

</head>
<body>
<div class="div0">
<div class="redbox"></div>
<div class="greenbox"></div>
<div class="bluebox"></div>
</div>
</body>
</html>

說明:

已知父元素的寬高為 width: 200px; height: 150px; ,

所以可知 top: calc(100%); 就是 top: 150px;,

margin-left: calc(100%); 就是 margin-left: 200px; 。

但值得注意的是 margin-top: calc(100%); 卻是等於 margin-top: 200px;,

照理來說應該等於 height 的 150px,可惜卻不是,是瀏覽器的 bug 嗎?

跟 calc 無關,是 margin 對於百分比屬性值似乎 spec 就已經規範是如此了。

Note that in a horizontal flow, percentages on ‘margin-top’ and ‘margin-bottom’ are relative to the width of the containing block, not the height (and in vertical flow, ‘margin-left’ and ‘margin-right’ are relative to the height, not the width).

 

參考資料:

Why does the page width affect “margin-top:50%” in Firefox?

8.3 Margin properties: 'margin-top', 'margin-right', 'margin-bottom', 'margin-left', and 'margin'

6.1. The margin properties