目录
Definition
CSS stands for Cascading Style Sheets
CSS描述了HTML元素在屏幕、纸张或其他媒体上的显示方式
CSS节省了大量的工作。它可以一次控制多个网页的布局
外部样式表(external stylesheet)存储在CSS文件中
Syntax
一个CSS声明由两部分组成:一个属性和一个值。属性是你想改变的样式的某个方面的名称;值是你想把它设置为什么。
为了使这个声明对HTML文档产生任何影响,它必须被应用于文档中的一个或多个元素。我们用一个选择器(selector)来做这件事。例如,你可以用p选择器选择一个网页中的所有元素。因此,如果你想把所有段落元素中的所有文本的颜色都变成红色,并且文字居中,设置字体,你可以使用下面的CSS规则集:
p{color:red; font-size: xx-large; text-align:center;}
多个选择器可以共享一个CSS规则集。我们可以用逗号分隔的列表来定位这些规则。例如,要将红色应用于p元素、h1元素和h2元素,我们可以使用以下规则集。
p,h1,h2{color:red;}
Selectors
• The element Selector • Based on the element name
• p { text-align: center;}
• The id Selector: • A hash (#) character, followed by the id of the element
• #para1 { text-align: center;}
• The class Selector • A period (.) character, followed by the name of the class
• .center { text-align: center;}
Add CSS code
established order of priority
1. Inline style (highest priority)
2. Internal style sheet (second priority)
3. External style sheet (third priority)
4. Web browser default (only if not defined elsewhere)
对于每个元素,浏览器将看到哪些样式是内联的,以及来自内部和外部样式表的定义。对于检测到的任何冲突,它将使用这个优先系统来决定在页面上显示哪种格式。例如:标题文本将以内联样式所指定的颜色显示,它比其他所有样式都要优先。如果在同一个样式表中定义了多个相互冲突的样式,那么只有最后的一个会被应用。要小心,因为这是另一个由初学者犯的常见错误。
Three Ways to Use CSS
1. Inline Style - CSS code is placed directly into an XHTML element within the <body> section of a web page:
You can use inline styles, which are applied directly to an element in the HTML document using the style attribute. The value of the style attribute is a CSS declaration block, meaning you can apply a semicolon-separated list of CSS declarations to the element.
2. Internal Style - CSS code is placed into a separate, dedicated area within the <head> section of a web page:
You can use a style element to add style information to an HTML document. The style element can be a child of either the head element or body element of a document. The head element tends to be preferable as the styles will be applied to your page more quickly.
3. External Style - CSS code is placed into a separate computer file and then linked to a web page:
You can provide a style sheet as an external resource using the link element. One of the rationalities behind style sheets is the separation of concerns, which is why this approach is often recommended.
body{background-color: powderblue;}
h1{color:blue}
h2{color:red}
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1>heading</h1>
<h2>2nd heading<h2>
</body>
</html>