DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS進階教程
網頁製作:CSS 細節優化筆記大集合
編輯:CSS進階教程     

以下把日常做頁面時反覆用到的 CSS(與少量 JS)細節整理成八個主題,都是些小地方,但累積起來很影響成品的完成度。

細節一:對齊、編輯器與視窗相關

文字與圖片底對齊

<li>記住密碼<img src="" align="bottom" style="margin-bottom:-4px"/></li>

文字與圖片居中對齊

<li>記住密碼<img src="static/img/xyx.jpg" align="middle"/></li>

更換 IE「檢視原始碼」開啟的編輯器

  1. 開啟登錄檔編輯器(開始 → 執行 → 輸入 regedit)
  2. 找到 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Internet Explorer\View SourceEditor\Editor Name,把預設值改為你的編輯器路徑,例如 D:\Program Files\EmEditor\EmEditor.exe
  3. 回到 IE 用「檢視原始碼」即可看到效果
  4. 若 Editor Name 這個機碼不存在,自行新增一項即可

讓視窗自動最大化

在 <body> 與 </body> 之間加入:

<script language="javascript">
setTimeout('top.moveTo(0,0)', 5000);
setTimeout('top.resizeTo(screen.availWidth, screen.availHeight)', 5000);
</script>

window.opener 是什麼

它指向以 window.open 開啟的那個視窗的父視窗。若父視窗 parentForm 用 window.open("subForm.html") 開啟子頁,那麼在 subForm.html 中,window.opener 就代表 parentForm,可藉此設定父視窗的值或呼叫其方法:

window.opener.test();  // 呼叫父視窗的 test()

if (window.opener && !window.opener.closed) {
    window.opener.document.parentForm.stockBox.value = symbol;
}

重新整理頁面的方法

JavaScript 可用的寫法:

history.go(0)
location.reload()
location = location
location.assign(location)
document.execCommand('Refresh')
window.navigate(location)
location.replace(location)
document.URL = location.href

自動重新整理/跳轉:

<!-- 20 秒後重新整理 -->
<meta http-equiv="refresh" content="20">

<!-- 20 秒後跳轉 -->
<meta http-equiv="refresh" content="20;url=https://www.poluoluo.com">

<script language="JavaScript">
function myrefresh() { window.location.reload(); }
setTimeout('myrefresh()', 1000);  // 每秒刷新一次
</script>

重新整理框架:

// 刷新包含該框架的頁面
<script language=JavaScript>parent.location.reload();</script>

// 子視窗刷新父視窗
<script language=JavaScript>self.opener.location.reload();</script>

// 刷新另一個框架
<script language=JavaScript>parent.另一FrameID.location.reload();</script>

用底線命名不是好習慣

用過 CSS hack 的人都知道,以底線開頭的寫法(如 _style)本身就是一種 hack,能讓 IE 以外的多數瀏覽器忽略該宣告。因此把 _ 當作命名分隔符並不合規範,做 CSS 檢查時會出現錯誤提示。

IE 條件註釋

<!--[if !IE]>除 IE 外都可識別<![endif]-->
<!--[if IE]> 所有的 IE 可識別 <![endif]-->
<!--[if IE 5.0]> 只有 IE5.0 可以識別 <![endif]-->

常見 CSS hack 寫法

/* 第一種 */
.div {
  background: orange;
  *background: green !important;
  *background: blue;
}

/* 第二種 */
.div {
  margin: 10px;
  *margin: 15px;
  _margin: 15px;
}

/* 第三種 */
#div { color: #333; }
*+html #div { color: #999; }
* html #div { color: #666; }

細節二:IE6/IE7 常見狀況

IE6 及以下不支援 a 以外的 :hover

在 Firefox、IE7 上正常的效果,到了 IE6 就失效。解法是改用類名切換:

#show li.s1{ border:1px solid #ff9900; background:#454242;}
#show li.s2{ border:1px solid #D9D8D8; background:#312E2E;}

<li onMouseOver="this.className='s1'" onMouseOut="this.className='s2'"></li>

為元素觸發 hasLayout

許多 IE6/IE7 的怪問題可以靠觸發 hasLayout 解決。最簡單的方式是給 height 或 width(zoom 也可以,但它不是 CSS 標準的一部分),例如 height:1%。若父元素未設高度,元素實際高度不會改變,但已經具備 hasLayout 屬性。

IE6 下字元重複出現

display: inline;      /* 確保浮動元素加上這行 */
margin-right: -3px;   /* 在浮動元素上使用 */

樣式優先級

  1. 行內樣式 [1.0.0.0]
  2. ID 選擇器 [0.1.0.0]
  3. 類別/屬性/偽類選擇器 [0.0.1.0]
  4. 元素標籤/偽元素選擇器 [0.0.0.1]

單一元素垂直居中

#exm{
    position: absolute;
    left: 50%;
    top: 50%;
    z-index: 1;
    width: 200px;
    height: 100px;
    margin-left: -100px;
    margin-top: -52px;
}

zoom 屬性

zoom: normal | number,用來設定或取得物件的縮放比例。變更已被呈遞物件的值會導致周圍內容重新流動。此屬性不可繼承,但會影響物件的所有子物件。

圖文並排時垂直居中

  1. 將 line-height 設為圖片高度或圖片父元素高度
  2. 再將圖片設為 vertical-align: middle;

li 內含 a 與 img 時 IE6 出現空白

四種解法:

  • 讓 li 浮動,並將 img 設為區塊元素
  • 將 ul 設為 font-size:0;
  • 將 img 設為 vertical-align: bottom;
  • 將 img 設為 margin-bottom: -5px;

細節三:換行、高度與對齊的通用解法

  • 已造訪過的連結失去 hover/active:調整 CSS 宣告順序為 L-V-H-A(link、visited、hover、active)。
  • Firefox 下連續長字串不換行:word-wrap:break-word; overflow:hidden;
  • Firefox 下父容器高度不自適應:清除子元素的浮動。
  • IE 下圖片下方出現空隙:將 img 設為 display:block,或把 vertical-align 設為 top/bottom/middle/text-bottom;也可把父容器 font-size 設為 0。
  • IE6 下浮動元素與相鄰非浮動元素間有 3px 間隙:讓相鄰元素也浮動,或對 IE6 指定 _margin-right:-3px;
  • li 內容過長時以省略號顯示:white-space:nowrap; text-overflow:ellipsis; -o-text-overflow:ellipsis; overflow:hidden;
  • 文字無法垂直居中:讓 line-height 等於容器高度。
  • 輸入框與相鄰文字對不齊:為輸入框加上 vertical-align:middle;
  • IE6 無法定義高度為 1px 的容器:加上 overflow:hidden、zoom:0.8、line-height:1px。

IE 自訂捲軸樣式:

body{
  scrollbar-face-color: #f6f6f6;
  scrollbar-highlight-color: #fff;
  scrollbar-shadow-color: #eeeeee;
  scrollbar-3dlight-color: #eeeeee;
  scrollbar-arrow-color: #000;
  scrollbar-track-color: #fff;
  scrollbar-darkshadow-color: #fff;
}

細節四:Flash 疊層、置中與收藏

  • 讓 DIV 顯示在 Flash 之上:為 Flash 加上 <param name="wmode" value="transparent" /> 或 value="opaque"。
  • 讓一個層在瀏覽器中垂直居中:百分比絕對定位搭配負 margin。
position: absolute;
top: 50%;
left: 50%;
margin: -100px auto auto -100px;
width: 200px;
height: 200px;

加入收藏夾:

<script type="text/javascript">
// <![CDATA[
function bookmark(){
  var title = document.title;
  var url = document.location.href;
  if (window.sidebar) window.sidebar.addPanel(title, url, "");
  else if (window.opera && window.print) {
    var mbm = document.createElement('a');
    mbm.setAttribute('rel', 'sidebar');
    mbm.setAttribute('href', url);
    mbm.setAttribute('title', title);
    mbm.click();
  }
  else if (document.all) window.external.AddFavorite(url, title);
}
// ]]>
</script>
<a href="javascript:bookmark()">加入收藏夾</a>

細節五:幾個實用片段

常見新聞列表寫法

<ul class="list">
  <li><span>2006年6月6日 </span><a href="#">新聞標題01</a></li>
  <li><span>2006年6月6日 </span><a href="#">新聞標題02</a></li>
</ul>

IE 的漸層背景(Firefox 與 Chrome 不支援)

/* 由上而下 */
body{filter: progid:DXImageTransform.Microsoft.Gradient(gradientType=0,startColorStr=#ffffff,endColorStr=#000000);}

/* 由左而右 */
body{FILTER: progid:DXImageTransform.Microsoft.Gradient(gradientType=1,startColorStr=#ffffff,endColorStr=#000000);}

border:none 與 border:0 的差別

理論上,border:0 雖然看不見,瀏覽器仍會對 border-width/color 進行渲染,佔用記憶體;border:none 則不執行渲染動作。相容性上,在 IE6/IE7 對 button、input 這類標籤時,none 似乎無效、邊框仍在,而 0 反而能讓所有瀏覽器一致隱藏邊框。若一定要讓 none 全相容,只要在同一選擇器上加一條背景屬性即可。

多欄等高布局(正內距+負外距)

.e { padding-bottom: 32767px; margin-bottom: -32767px; }

細節六:innerText、innerHTML 與 outerHTML

以 <div id="test"><span>test1</span>test2</div> 為例:

  • test.innerText → test1 test2(不含標籤)
  • test.innerHTML → <span>test1</span>test2
  • test.outerHTML → <div id="test"><span>test1</span>test2</div>(含自身標籤)

其他常記混的幾點:

  • Number():參數含任何非數字字元時結果為 NaN;parseInt():由左而右盡量轉換,遇到非數字即停止;isNaN():參數不是數字時回傳 true。
  • 若 a = "23.50abc",則 typeof a 為 String、parseFloat(a) 為 23.5、parseInt(a) 為 23、Number(a) 為 NaN。
  • JS 變數名可用數字、字母、美元符號與底線,但不可以數字開頭。
  • getElementsByTagName() 需等文件載入完成後才取得到。
  • nodeType 共 12 種,1 代表元素節點,3 代表文字節點;nodeName 為節點名稱(文字節點則是 #text);nodeValue 為節點的值。
  • 父到子:childNodes 只列出第一層子節點;firstChild = childNodes[0];lastChild = childNodes[childNodes.length-1];hasChildNodes() 回傳布林值。
  • 子到父:var parentElm = myLinkItem.parentNode;,可用 while 迴圈一路往上找。
  • 修改元素屬性有兩種方式:直接以物件屬性存取(mainImage.src = ''),或用 getAttribute()/setAttribute()。

細節七:幾個好用的小函式

// 取到指定小數位
function roundTo(base, precision) {
  var m = Math.pow(10, precision);
  return Math.round(base * m) / m;
}
roundTo(3.942487, 3);  // 3.942

// 指定範圍內的隨機整數
function randomBetween(min, max) {
  return min + Math.floor(Math.random() * (max - min + 1));
}

// 數字轉字串
var a = 10;
a = String(a);   // 或 a = a.toString();

// URL 編碼
var b = escape("https://www.google.com/directoryname/?p=e");

// 改變元素類型(p → div):建立 div,搬移 p 的子節點,再以 div 取代 p

// 函式需要幾個參數
function add(n1, n2) {}
add.length;   // 2

// 函式實際收到幾個參數
function add(n1, n2) { return arguments.length; }

細節八:inline-block、清除浮動與小技巧

跨瀏覽器的 inline-block

.element-class {
  display: -moz-inline-stack;  /* Firefox */
  display: inline-block;       /* 標準瀏覽器 */
  zoom: 1;                     /* IE */
  *display: inline;            /* 只有 IE 認得(CSS Hack) */
}

清除浮動

.clearfix:after {
  visibility: hidden;
  display: block;
  font-size: 0;
  content: " ";
  clear: both;
  height: 0;
}
.clearfix { zoom: 1; }

在網址列顯示自訂圖示

先製作 16×16 像素、副檔名為 ico 的圖示並上傳,然後在 <head> 之間加入:

<link rel="ICON" href="https://圖片網址">

若使用者以 IE5 以上版本瀏覽,只要把圖片放在網站根目錄即可自動辨識。

IE6 中區塊容器高度無法小於某值

例如 <p style="height:1px;"></p>,解法是加上 overflow:hidden。

文字以省略號截斷

div {
  width: 200px;
  height: 100px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

這些都是些零碎的小東西,平時整理成自己的片段庫,做頁面的時候會省下不少反覆查資料的時間。

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