如何在 HTML 页面中添加 CSS

cssweb developmentfront end technologyhtml更新于 2025/1/19 3:56:17

我们可以通过三种方式在 HTML 页面中添加 CSS。它们是 −

  • 内联

    我们在元素的 style 属性中指定 CSS 样式。但是,建议使用 CSS 的内部或外部链接来实现文件模块化。

  • 内部

    我们可以在 HTML 文档的 <head> 内的 <style> 标签中包含 CSS 规范。

  • 外部

    我们可以使用 <link> 标签链接本地或服务器上的 .css 文件。通过使用外部链接重构文件,我们可以获得一个可在多个网页上使用的通用 CSS 文件。

语法

在 HTML 中包含 CSS 文件的语法如下

/*inline*/
<element style="/*declarations*/"></element>
/*internal*/
<head>
<style>
/*declarations*/
</style>
</head>
/*external*/
<head>
<link rel="stylesheet" href="#location">
</head>

示例

以下示例说明了如何将 CSS 文件包含在 HTML 页面中

内联 CSS

<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div style="background-color:mistyrose; height: 50px;"></div>
<p style="letter-spacing: 16px; font-size: 1.3em;">
<u>Demo text here</u>
</p>
</body>
</html>

输出

这将给出以下输出 −

示例

Internal linking

<!DOCTYPE html>
<html>
<head>
<style>
table, table *{
   border: 5px double green;
   margin: auto;
   padding: 20px;
}
tr {
   box-shadow: 0 0 0 3px red;
}
td {
   border-color: blue;
}
</style>
</head>
<body>
<table>
<tr>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
</tr>
</table>
</body>
</html>

输出

这将给出以下输出 −

示例

External linking

HTML file

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

CSS file

div {
   margin: auto;
   padding: 15px;
   width: 33%;
   border: 2px solid;
   border-radius: 50%;
}
div > div {
   border-color: green;
}
div > div > div {
   border-color: red;
}

输出

这将给出以下输出 −


相关文章


有用资源