在 HTML 文档中包含 CSS
将 CSS 添加到 HTML 文档可 улучшить внешний вид своей网页。可以轻松添加图像、边框、边距、颜色的各种样式。要将 CSS 包含在 HTML 文档中,我们可以将它们内部包含、内联包含或链接到外部文件。让我们通过示例来理解它们。
语法
在 HTML 中包含 CSS 文件的语法如下所示 −
/*inline*/
<element style="/*declarations*/"></element>
/*internal*/
<head>
<style>
/*declarations*/
</style>
</head>
/*external*/
<head>
<link rel="stylesheet" href="#location">
</head>
以下示例显示了在 HTML 文档中链接 CSS 文件 −
内联 CSS
使用内联 CSS,使用样式属性并设置 CSS 样式;
示例
<!DOCTYPE html> <html> <body> <p style="font-family: Forte;">Demo text</p> <p style="background-color: lightblue;">This is Demo text</p> <img src="https://tutorialspoint.com/memcached/images/memcached.jpg" style="border: 3px groove orange;"> </body> </html>
内部链接
对于内部链接,使用 <style> 元素。在此元素下,指定 CSS 样式 −
<style> <!-- Add the styles --> </style>
示例
我们来看一下示例 −
<!DOCTYPE html>
<html>
<head>
<style>
div {
margin: auto;
padding: 15px;
width: 33%;
border: 2px solid;
border-radius: 5%;
}
div > div {
border-color: transparent;
box-shadow: inset 0 0 6px red;
}
div > div > div {
border-color: red;
}
</style>
</head>
<body>
<div>
<div></div>
<div>
<div></div>
</div>
<div></div>
</div>
</body>
</html>
外部链接
在网页上,你还可以包含一个外部 css 文件,并放置 css 样式。可以通过 HTML 文件引用相同的 CSS 文件,如下面的示例所示。<link> 元素用于链接外部文件 style.css −
<link rel="stylesheet" type="text/css" href="style.css">
示例
我们来看一下示例 −
<!DOCTYPE html> <html> <head> <link rel="stylesheet" type="text/css" href="style.css"> </head> <body> <p>Demo text</p> <p>Demo text again</p> </body> </html>
以下是外部 style.css 文件 −
p {
text-decoration: overline;
text-transform: capitalize;
}
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP