CSS



簡介

CSS層疊樣式表的縮寫。它有助於將HTML元素的表示形式定義為一個單獨的檔案,該檔案稱為CSS檔案,副檔名為.css

CSS可以透過在一個地方進行更改來更改任何HTML元素的格式。所做的所有更改都會自動反映到該元素出現在其中的網站的所有網頁中。

CSS規則

CSS規則是我們為了建立樣式表而必須建立的樣式。這些規則定義了關聯HTML元素的外觀。CSS語法的通用形式如下

Selector {property: value;}

關鍵點

  • 選擇器是應用CSS規則的HTML元素。

  • 屬性指定要更改的選擇器對應的屬性。

  • 屬性可以取指定的值。

  • 屬性和值之間用冒號(:)分隔。

  • 每個宣告之間用分號(;)分隔。

以下是CSS規則的示例

P { color : red;}

h1 (color : green; font-style : italic }

body { color : cyan; font-family : Arial; font- style : 16pt}

將CSS嵌入到HTML中

以下是將CSS新增到HTML文件的四種方法。

  1. 內聯樣式表

  2. 嵌入式樣式表

  3. 外部樣式表

  4. 匯入樣式表

內聯樣式表

內聯樣式表包含在HTML元素中,即它們與元素內聯放置。要新增內聯CSS,我們必須宣告style屬性,該屬性可以包含任何CSS屬性。

語法

<Tagname STYLE = “ Declaration1 ; Declaration2 “>  …. </Tagname>

讓我們考慮以下使用內聯樣式表的示例

<p style="color: blue; text-align: left; font-size: 15pt">
Inline Style Sheets are included with HTML element i.e. they are placed inline with the element.
To add inline CSS, we have to declare style attribute which can contain any CSS property.
</p>

輸出 -

Inline Style Sheet

嵌入式樣式表

嵌入式樣式表用於將相同的外觀應用於特定元素的所有出現。這些是在<head>元素中使用<style>元素定義的。

<style>元素必須包含type屬性。type屬性的值指定在瀏覽器呈現時包含哪種型別的語法。

語法

<head> <title> …. </title>
   <style type =”text/css”>
      …….CSS Rules/Styles….
   </style>		
</head>

讓我們考慮以下使用嵌入式樣式表的示例

<style type="text/css">
   p {color:green; text-align: left; font-size: 10pt}
   h1 { color: red; font-weight: bold}
</style>
Embedded Style Sheet

外部樣式表

外部樣式表是包含CSS規則的單獨.css檔案。這些檔案可以透過使用帶有rel屬性的<link>標記連結到任何HTML文件。

語法

<head> <link rel= “stylesheet”  type=”text/css” href= “url of css file”>
</head>

為了建立外部css並將其連結到HTML文件,請按照以下步驟操作

  • 首先建立一個CSS檔案,併為多個HTML元素定義所有CSS規則。讓我們將此檔案命名為external.css。

p{ 
   Color: orange;     text-align:  left;        font-size: 10pt;
}
h1{ 
   Color: orange;      font-weight: bold;
}
  • 現在建立一個HTML文件並將其命名為externaldemo.html。

<html>
   <head>
      <title> External Style Sheets Demo </title>
      <link rel="stylesheet"  type="text/css" href="external.css">
   </head>
   <body>
      <h1> External Style Sheets</h1>
      <p>External Style Sheets are the separate .css files that contain the CSS rules.</p>
   </body>
</html>
External Style Sheet

匯入樣式表

匯入樣式表允許我們從其他樣式表匯入樣式規則。要匯入CSS規則,我們必須在樣式表中的所有規則之前使用@import。

語法

<head><title> Title Information </title>
   <style type=”text/css”>
      @import URL (cssfilepath)
      … CSS rules…
   </style>
</head>

讓我們考慮以下使用內聯樣式表的示例

<html>
   <head>
      <title> External Style Sheets Demo </title>
      <style>
         @import url(external.css);
      </style>
   </head>
   <body>
      <h1> External Style Sheets</h1>
      <p>External Style Sheets are the separate .css files that contain the CSS rules.</p>
   </body>
</html>
Imported Style Sheet
廣告