CSS 中的外部樣式表匯入


在另一個 CSS 宣告中匯入額外的 CSS 檔案。為此,使用 @import 規則,因為它將樣式錶鏈接到文件中。通常,當一個樣式表依賴於另一個樣式表時,就會使用此規則。它在文件頂部指定,位於 <head> 內的 @charset 宣告之後。除此之外,也可以使用 <link> 元素。

語法

@import 規則的語法如下所示: -

@import /*url or list-of-media-queries*/

媒體查詢可以是複合語句,這些語句可以指定文件在不同媒體中的行為。

使用 @import 規則匯入外部樣式表

以下示例實現了 @import 規則。使用 @import,我們已包含 style.css 檔案 -

@import url(style.css);
body {
   background-color: honeydew;
}

@import 規則用於此目的,因為它將樣式錶鏈接到文件中。樣式檔案包括此 HTML 文件的樣式。讓我們來看示例 -

示例

<!DOCTYPE html>
<html>
<head>
   <style type="text/css">
      @import url(style.css);
      body {
         background-color: honeydew;
      }
   </style>
</head>
<body>
   <p>This is demo paragraph one.</p>
   <p class="two">This is demo paragraph two.</p>
   <p>This is demo paragraph three</p>
</body>
</html>

style.css

p { color: navy; font-style: italic; }
.two { color: darkgreen; font-size: 24px; }

使用元素包含外部樣式表

讓我們看另一個示例,使用 <link> 元素匯入外部樣式表 -

HTML 文件

<!DOCTYPE html>
<html>
<head>
   <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
   <div></div>
</body>
</html>

style.css

div {
   height: 50px;
   width: 100px;
   border-radius: 20%;
   border: 2px solid blueviolet;
   box-shadow: 22px 12px 3px 3px lightblue;
   position: absolute;
   left: 30%;
   top: 20px;
}

更新於: 2023 年 12 月 21 日

2K+ 瀏覽量

開啟您的職業生涯

透過完成本課程獲得認證

開始
廣告