参考资料: W3school-CSS 教程
CSS基础
- CSS的规则由(选择器 + 声明)构成
- CSS是默认继承的
基础示例
示例代码:
提示:以下例子中的 CSS 代码均位于 HTML 的 head 部分,这样做的目的是为了利于演示例子本身。在实际的开发中,使用 CSS 最好的方式是引用外部样式表。
<html>
<head>
<style type="text/css">
body {background-color: yellow}
h1 {background-color: #00ff00}
h2 {background-color: transparent}
p {background-color: rgb(250,0,255)}
p.no2 {background-color: gray; padding: 20px;}
</style>
</head>
<body>
<h1>这是标题 1</h1>
<h2>这是标题 2</h2>
<p>这是段落</p>
<p class="no2">这个段落设置了内边距。</p>
</body>
</html>
语法解释
CSS 规则由两个主要的部分构成:选择器,声明。
- 多条声明
- 选择器分组
selector {declaration1; declaration2; ... declarationN }
selector {property: value}
h1 {color:red; font-size:14px;}
h2,h3,h4,h5,h6 {
color: green;
}
继承
子元素从父元素继承属性。
body {
font-family: Verdana, sans-serif;
}
属性 | 描述 |
---|---|
font-family | 规定文本的字体系列 |
通过 CSS 继承,子元素将继承最高级元素(在本例中是 body
)所拥有的属性(这些子元素诸如 p
, td
, ul
, ol
, ul
, li
, dl
, dt
,和 dd
),不需要另外的规则。
CSS派生选择器
通过元素的上下文关系来定义样式
代码片段如下:
li strong {
font-style: italic;
font-weight: normal;
}
效果查看,效果展示↓