[LESS]使用LESS讓CSS更好維護

  • 2037
  • 0
  • CSS
  • 2013-07-05

使用LESS讓CSS更好維護

在使用Layout時,常常會讓一些區塊置中,使用方式可以先讓位置在left:50%的地方,然後再設定margin-left為負區塊寬度的一半,如下#content的樣式,


<!DOCTYPE html>
<html>
<head>
    <title>水平置中測試</title>
    <style>
        html,
        body {
            height: 100%;
        }

        #wrapper {
            position: relative;
            height: 100%;
        }

        #content {
            position: absolute;
            left: 50%;
            width: 600px;
            height: 100%;
            margin: 0px 0px 0px -300px;
            background-color: #00ff00;
        }
    </style>
</head>
<body>
    <div id="wrapper">
        <div id="content">
            水平置中測試
        </div>
    </div>
</body>
</html>

image

 

而從CSS這就可以發現我們要手動去計算區塊的一半(300px)。

這時,我們可以使用LESS(使用方式跟TypedScript的Fu還蠻像的),將區塊的寬度定義成變數,然後使用 -變數/2 (-@the-width/2) 就可以了,如下圖所示,

image


html, body {
            height: 100%;
        }

        #wrapper {
            position: relative;
            height: 100%;
        }

        #content {
            position: absolute;
            left: 50%;
            width: @the-width;
            height: 100%;
            margin: 0px 0px 0px -@the-width/2;
            background-color: #00ff00;
        }
@the-width:600px;

而頁面就Link VS2012 產生出來的css就可以了哦!

image

 

所以下次如果要修改寬度的話,也只要修改@the-width這個變數的值,比如說從600px改成800px,就可以了!

 

特別感謝點部落團隊舉辦 HTML 5 & JavaScript 程式開發實戰贈書活動,讓筆者可以獲得 HTML 5 & JavaScript 程式開發實戰 這本好書。

Hi, 

亂馬客Blog已移到了 「亂馬客​ : Re:從零開始的軟體開發生活

請大家繼續支持 ^_^