Paano magdagdag ng CSS
- Previous Page Selector ng CSS
- Next Page Comment ng CSS
Kapag binabasa ng browser ang table ng estilo, ito ay maghahalintulad ng dokumentong HTML ayon sa impormasyon ng table ng estilo.
Tatlong paraan sa paggamit ng CSS
May tatlong paraan upang idagdag ang table ng estilo:
- Estilo ng Labas CSS
- 內部 CSS
- 行內 CSS
Estilo ng Labas CSS
Sa pamamagitan ng paggamit ng estilo ng labas na table, puwede mong baguhin ang kabuuan ng anyo ng websayt sa pamamagitan ng pagbabago ng isang lamang file!
Ang bawat pahina ng HTML ay dapat magkaroon ng pagtutukoy sa file ng estilo ng labas sa <link> na elemento sa bahagi ng head.
範例
Ang estilo ng labas ay inidinagdag sa <head> na bahagi ng pahina ng HTML sa pamamagitan ng elemento <link>:
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
外部樣式表可以在任何文本編輯器中編寫,並且必須以 .css 扩展名保存。
外部 .css 文件不應包含任何 HTML 標籤。
"mystyle.css" 是這樣的:
"mystyle.css"
body { background-color: lightblue; } h1 { color: navy; margin-left: 20px; }
注意:請勿在屬性值和單位之間添加空格(例如 margin-left: 20 px;
)。正確的寫法是:margin-left: 20px;
內部 CSS
如果一張 HTML 頁面擁有唯一的樣式,那麼可以使用內部樣式表。
內部樣式是在 head 部分的 <style> 元素中進行定義。
範例
內部樣式在 HTML 頁面的 <head> 部分內的 <style> 元素中進行定義:
<!DOCTYPE html> <html> <head> <style> body { background-color: linen; } h1 { color: maroon; margin-left: 40px; } </style> </head> <body> <h1>This is a heading</h1> <p>This is a paragraph.</p> </body> </html>
行內 CSS
行內樣式(也稱為內聯樣式)可用於為單個元素應用唯一的樣式。
如需使用行內樣式,請將 style 屬性添加到相關元素。style 屬性可包含任何 CSS 屬性。
範例
行內樣式在相關元素的 "style" 屬性中定義:
<!DOCTYPE html> <html> <body> <h1 style="color:blue;text-align:center;">This is a heading</h1> <p style="color:red;">This is a paragraph.</p> </body> </html>
提示:行內樣式失去了樣式表的許多優點(通過將內容與呈現混合在一起)。請謹慎使用此方法。
多個樣式表
如果在不同樣式表中為同一選擇器(元素)定義了一些屬性,則將使用最後讀取的樣式表中的值。
假設某個外部樣式表為 <h1> 元素設置的如下樣式:
h1 { color: navy; }
然後,假設某個內部樣式表也為 <h1> 元素設置了如下樣式:
h1 { color: orange; }
範例
如果內部樣式是在鏈接到外部樣式表之後定義的,則 <h1> 元素將是橙色:
<head> <link rel="stylesheet" type="text/css" href="mystyle.css"> <style> h1 { color: orange; } </style> </head>
範例
不過,如果在鏈接到外部樣式表之前Defined internal style, then the <h1> element will be dark blue:
<head> <style> h1 { color: orange; } </style> <link rel="stylesheet" type="text/css" href="mystyle.css"> </head>
Cascading Order
When multiple styles are specified for a certain HTML element, which style will be used?
All styles in the page will be 'cascaded' into a new 'virtual' stylesheet according to the following rules:
- Inline Styles (in HTML elements)
- External and Internal Style Sheets (in the head section)
- Browser Default Styles
Therefore, inline styles have the highest priority and will override external and internal styles as well as browser default styles.
- Previous Page Selector ng CSS
- Next Page Comment ng CSS