Skip to content

基础知识

CSS 是一种描述 HTML 文档样式的语言,即层叠样式表。

样式声明

有三种插入样式表的方法:

  • 外部 CSS
  • 内部 CSS
  • 行内 CSS

外部 CSS

HTML 页面必须在 head 部分的 <link> 元素内包含对外部样式表文件的引用。

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

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
属性说明
rel定义当前文档与被链接文档之间的关系
href外部样式文件
type文档类型

内部 CSS

使用 style 标签可以在文档内部定义样式规则。

html
<!DOCTYPE html>
<html>
<head>
<style>
body {
  background-color: linen;
}

h1 {
  color: maroon;
  margin-left: 40px;
} 
</style>
</head>
<body>

<h1>This is a heading</h1>
<p>This is a paragraph.</p>

</body>
</html>

行内 CSS

行内样式(也称内联样式)可用于为单个元素应用唯一的样式。

html
<!DOCTYPE html>
<html>
<body>

<h1 style="color:blue;text-align:center;">This is a heading</h1>
<p style="color:red;">This is a paragraph.</p>

</body>
</html>

导入样式

使用 @import 可以在原样式规则中导入其他样式表,可以在外部样式、style标签中使用。

可以使用以下两种方式导入

css
@import "hd.css"				
@import url("hd.css")

导入样式要放在样式规则前面定义。

html
<style>
	@import url("hdcms.css");
	body {
		background: red;
	}
</style1>

初始样式

有些标签默认含有内外边距,且不同浏览器大小也不一样。为了统一我们可以重置标签的 CSS 默认样式。

最简单的方式就是使用插件css-reset完成,你也可以在 vscode 等编辑器中定义代码片段。

html
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/meyer-reset/2.0/reset.min.css" />
css
html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, article, aside, canvas, details, embed, figure, figcaption, footer, header, hgroup, menu, nav, output, ruby, section, summary, time, mark, audio, video {
    margin:0;
    padding:0;
    border:0;
    font-size:100%;
    font:inherit;
    vertical-align:baseline
}
article, aside, details, figcaption, figure, footer, header, hgroup, menu, nav, section {
    display:block
}
body {
    line-height:1
}
ol, ul {
    list-style:none
}
blockquote, q {
    quotes:none
}
blockquote:before, blockquote:after, q:before, q:after {
    content:'';
    content:none
}
table {
    border-collapse:collapse;
    border-spacing:0
}

层叠顺序

当为某个 HTML 元素指定了多个样式时,会使用哪种样式呢?

页面中的所有样式将按照以下规则“层叠”为新的“虚拟”样式表,其中第一优先级最高:

  1. 行内样式(在 HTML 元素中)
  2. 外部和内部样式表(在 head 部分)
  3. 浏览器默认样式

因此,行内样式具有最高优先级,并且将覆盖外部和内部样式以及浏览器默认样式。