DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS詳解
純 CSS 做斜角:border 交界原理與四向實作
編輯:CSS詳解     

元素的內容高度為 0、寬度為 0,但 border 卻有厚度時,四條邊會在轉角處沿對角線斜切相接。把其中幾條邊設為透明,剩下的實色部分看起來就是一個三角形。這正是純 CSS 斜角的核心原理,稍作變化就能組出箭頭、對話框尖角等更多形狀。

單角:修掉容器的左上角

#corner {
  position: relative;
  top: -1px;
  left: -1px;
  width: 0;
  height: 0;
  overflow: hidden;
  border-top: 15px solid #fff;
  border-right: 15px solid #ccc;
}

配合一個 200px 寬、1px 灰邊的容器,就能做出「外框線在左上角被切掉」的效果。

完整範例

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>CSS 斜角示範</title>
<style type="text/css">
* { margin: 0; padding: 0; list-style: none; }
body { font-size: 63%; }
#wrapper {
  margin: 20px;
  width: 200px;
  border: 1px solid #ccc;
  font-size: 1.2em;
}
#corner {
  position: relative;
  top: -1px; left: -1px;
  width: 0; height: 0;
  overflow: hidden;
  border-top: 15px solid #fff;
  border-right: 15px solid #ccc;
}
#wrapper p { padding: 5px; text-indent: 20px; }

/* 四個方向的三角形 */
#joy_left {
  width: 20px; height: 0; overflow: hidden;
  border-top: 20px solid green;
  border-left: 20px solid #FFF;
}
#joy_top {
  position: relative; top: -20px;
  width: 0; height: 20px;
  border-top: 20px solid #FFF;
  border-right: 20px solid red;
}
#joy_bottom {
  position: relative; left: -40px; top: 20px;
  width: 0; height: 20px;
  border-left: 20px solid blue;
  border-bottom: 20px solid #FFF;
}
#joy_right {
  position: relative; left: -40px; top: 20px;
  width: 20px; height: 0; overflow: hidden;
  border-right: 20px solid #FFF;
  border-bottom: 20px solid #666;
}
.por { position: relative; float: left; }
</style>
</head>
<body>
<div id="wrapper">
  <div id="corner"></div>
  <p>內容一</p>
  <p>內容二</p>
  <p>內容三</p>
</div>
<div id="joy_left" class="por"></div>
<div id="joy_top" class="por"></div>
<div id="joy_bottom" class="por"></div>
<div id="joy_right" class="por"></div>
</body>
</html>

幾個實作提醒

三角形必須靠 width 與 height 歸零才會出現,任何一邊有內容高度,斜切就消失。

要哪個方向尖,就把那條邊設為實色,其餘設透明。想朝上就留 border-bottom,想朝右就留 border-left。

IE6/7 對透明 border 會顯示成黑邊,舊專案可用 border-color: transparent 搭配 hack,或直接改成與背景同色來繞過。

需要沿斜線放內容時,記得加 overflow: hidden,否則文字會溢出三角形範圍。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved