11.05.2008

CSS 圓角框製作

如果大家都用Firefox自然就沒有這篇教學啦,"-moz-border-radius" 就可以搞定一切,不過很可惜,目前 IE 仍舊是佔有率最高的瀏覽器,所以只好想辦法用多數倍的手續來達到圓角的效果。

利用背景圖做圓角有很多方法,在未知高度、寬度確定的情況下,最簡易的方案是 Sliding Doors,也就是將原圖切成上下兩張,一張給<div>,一張給DIV底下的<bd>。這裡教的方式是在寬度未知,或是同樣背景可能會應用在多種寬度的情況下,這時不可能再切多種寬度的背景,太麻煩了,改用現在的“定位”方案將可大量減少圖片量以及CSS Code。

首先畫出要的圓角圖,並將該圖整個切出。圖片大小可自己掌握,只切出一個圓都可以,只要到時處理 CSS 時能抓到圓的半徑寬度即可。

Html 按照一般方式給標籤與內容,特別的地方是要再多給四個div來處理四個圓角:

<div class="tab">
<h5>IE6 1px gap on absolute elements</h5>
<p class="content">I get a number of requests for help with rounded corners each week and the common problem is that ie is one pixel out on the bottom corners and on the right corners.</p>
<div class="round top-left"></div>
<div class="round top-right"></div>
<div class="round bottom-left"></div>
<div class="round bottom-right"></div>
</div>

CSS 部分最外層的 div 給相對位置,將四個角相同屬性的部份拉出來(.round)給寬、高、背景圖以及絕對位置,然後再針對四個角給背景圖的位置:

.tab {position: relative;padding: 40px;width: 600px;background: #333;color: #fff;}
.tab .round {width: 12px;height: 12px;background: url(round-bg.gif) no-repeat;position: absolute;}
.tab .top-left {top: 0px;left: 0px;background-position: top left;}
.tab .top-right {top: 0px;right: 0px;background-position: top right;}
.tab .bottom-left {bottom: 0px;left: 0px;background-position: bottom left;_margin-bottom: -1px;}
.tab .bottom-right {bottom: 0px;right: 0px;background-position: bottom right;_margin-bottom: -1px;}

至於 _margin-bottom: -1px 這東西是針對 IE6 的 Hack,原因是 IE6 對於寬、高單位為單數時會自作聰明的自行多加 1pix,詳情請參考 IE 1px discrepancy

完整範例請參考這裡

筆者還在皮毛階段,針對這方法可延伸出更多進階技巧,另一個基本方案是將背景圖片放大(例如:1000 x 4000),這種方式就可以使用邊框,也可避免 IE6 多出來的那 1px 問題。

沒有留言: