Using the CSS calc() Function

calc() 是 CSS 的原生屬性,目前支援度雖然沒到 9x% 這麼多,但可以放心,目前許多活動網站我都用此寫法,也從未接受到類似客服(通常是以臉書廣告為曝光的活動網站,受眾年齡層廣泛)。

calc() is one of the native properties of CSS. Although it’s not fully supported by every browser, I’ve actually been using it in lots of campaign pages already (which are mostly exposed to target audiences of various ages via Facebook ads), and haven’t received any function feedbacks so far, so there’s no need to worry — it’s really a nice way to do math in code.

Explanation of the Property

calc() 顧名思義就是 calculate(計算) 的縮寫,他可以使用在單位計算上,寫法上特別注意的是計算符號前後需空格,例如:

calc() ,naming as the abbreviation of “calculate”, is a native CSS property to do simple math calculations, and most commonly used for the value of length units. Notice that a space need to be added before and after the calculation symbol, for example,

.dpp {
width: calc(100% - 20px);
width: calc(100% -20px); // not working
}

Element Arrangement

以往我們可能會寫 ‘%’ 來描述所有響應式元件的寬度及間距,如

Previously, we might use ‘%’ to describe all the width and margin of responsive components, such as,

.dpp_element {
width: 30%;
margin: 1.66%;
}

但設計師可能會跟你說:「我的間距一定要 10px !!」,這時我們就可以使用帥氣的 calc() 輕鬆解決

But the designers may tell you that “I want the margin to be fixed as 10px!” Then calc() can be an easy solution.

.dpp_element {
width: calc( 33% - 5px );
margin: 5px;
}

Page Layout

左右配置是常見手法,但在響應式網頁裡如果都用 ‘%’ 來區分,設計師可能會不喜歡覺得醜;這時我們也可利用 calc() 來計算出符合設計師幻想的配置!

Left and right configuration is commonly used in layouts. However, if you use “%” in response pages, designers probably won’t like the way it presents. Instead, using calc() can help us calculate the configuration the designers want.

.dpp_left_area {
width: 200px;
margin-right: 15px;
}
.dpp_right_area {
width: calc( 100% - 215px );
}

Responsive Full Screen Overlay with Navigation Bar

我們常常需要製作每屏滿版的網站,但這時候如果有固定高度的導覽列( Navigation Bar ),該怎麼辦呢?我也常常用 calc() 來解決這件事!

We often need to make websites with full screen overlay, but what should you do when the site contains a navigation bar with fixed height? calc () can solve this problem!

.dpp_nav {
position: fixed;
top: 0;
left: 0;
height: 50px;
}
.dpp_section {
width: 100%;
height: calc( 100vh - 50px );
}

如果認為固定 height 失去了一些彈性,其內容物可能會超過一屏高度,我們可以將 dpp_section 改寫成這樣:

If you consider fixed height has lost its flexibility because its content may exceed the screen height, we can revise the dpp_section like this:

.dpp_section {
width: 100%
height: auto;
min-height: calc( 100vh - 50px );
padding: 5% 0; // 如果你不想要上下貼緊緊的話
}

其他進階用法也可以在 background-postion, transform … 等單位做計算,甚至可以搭配 CSS 的 attr() 去做好玩的應用,未來將再來談談!

結論,要討好設計師,calc() 絕對是您的 css 好夥伴 !

More advanced usage can also apply to background-postion, transform and different calculation of units. Moreover, you can even use it with CSS attr() function, we’ll talk about more interesting application later.

To conclude, calc () is definitely a good CSS tool to satisfy designers!