HTML教程 - 样式

分享于 

5分钟阅读

html

  繁體

样式

CSS代表级联样式表,是web的可视化语言,有了它,我们可以设计HTML页面的外观,CSS允许在页面和数据之间分离,在HTML中编码,以及页面的样式。

CSS之所以"级联"是因为它定义了使用哪种样式的方式,HTML元素根据从低到高的一系列特定优先级,以"级联"方式继承它样式:

在加载顺序中定义的最后一个规则将生效 元素选择器(例如,设置所有<footer>元素的样式),类选择器(例如,设置所有.main元素的样式),ID选择器,用于在页面中选择特定元素,媒体类型(在媒体查询部分解释) 使用HTML "样式"属性定义元素特定的CSS important CSS覆盖指令(仅用作最后手段)!

此外,还有relative和relative 。

定义CSS

可以使用以下四种方法定义CSS :

1. inline

要使用inline方法定义CSS样式,请使用HTML,


<p>This is the default serif font. It is commonly used in 
printed media for better readability, since letters
are more distinct in serif fonts.</p>

<p style="font-family: sans-serif">This is a sans-serif font. 
It is commonly used in screens because it is hard
for screens to render letters with such great detail.</p>

不建议定义内联CSS,请尽量避免这样做,你应该始终定义一个CSS样式表并使用选择器来应用样式表,

以下是一个示例:


<!DOCTYPE html>
<head>
 <style>
 .nice {
 font-family: sans-serif;
 }
 </style>
</head>
<body>
 <p>This is the default serif font. It is commonly used in 
 printed media for better readability, since letters
 are more distinct in serif fonts.</p>

 <p class="nice">This is a sans-serif font. 
 It is commonly used in screens because it is hard
 for screens to render letters with such great detail.</p>

</body>

你可以在外部文件(通常以.CSS扩展名注明)中定义CSS样式表并加载它。

这是一个示例,用于定义与上一示例中定义的CSS类相同的示例,但是定义在名为" style.CSS "的文件中。


.nice {
 font-family: sans-serif;
}

要加载CSS文件,我们需要按以下方式使用<link> HTML标记:


<link rel="stylesheet" href="nice.css">

在本例中,HTML文件和CSS文件都需要位于同一个目录中。

链接标记应该定位在inside HTML页面的<head>部分,如下所示:


<!DOCTYPE html>
<head>
 <link rel="stylesheet" href="nice.css"> 
</head>
<body>
 <p>This is the default serif font. It is commonly used in 
 printed media for better readability, since letters
 are more distinct in serif fonts.</p>

 <p class="nice">This is a sans-serif font. 
 It is commonly used in screens because it is hard
 for screens to render letters with such great detail.</p>

</body>

4.编程访问

例如:


<!DOCTYPE html>
<body>
 <p id="serif-text">This is the default serif font. It is commonly used in 
 printed media for better readability, since letters
 are more distinct in serif fonts.</p>

 <p class="nice" id="sans-serif-text">This is a sans-serif font. 
 It is commonly used in screens because it is hard
 for screens to render letters with such great detail.</p>

 <script>
 var sansSerifText = document.getElementById("sans-serif-text");
 sansSerifText.style.fontFamily ="sans-serif";
 </script>
</body>


style  learn  教程  样式  
相关文章