这是我参与「第五届青训营 」伴学笔记创作活动的第2天。
本堂课重点
- CSS是什么
- 选择器
- 伪类
- 组合
- 继承
- CSS求值过程
- 块级与行级比较
详细知识介绍
CSS是什么
- Cascading Style Sheets
- 用来定义页面元素的样式
- 设置字体和颜色
- 设置位置和大小
- 添加动画效果
CSS选择器Selector
作用:找出页面中的元素,以便给他们设置样式 选择器有:
- 通配选择器
<h1>This is heading</h1>
<p>this is some paragraph.</p>
<style>
* {
color: red;
font-size: 20px;
}
</style>
- 标签选择器
<h1>This is heading</h1>
<p>this is some paragraph.</p>
<style>
h1 {
color: orange;
}
p {
color: gray;
font-size: 20px;
}
</style>
- id选择器
<h1 id="logo">
<img src="https://assets.codepen.io/59477/h5-logo.svg" alt="HTML5 logo" width="48" />
HTML5 文档
<h1>
<style>
#logo {
font-size: 60px;
font-weight: 200;
}
</style>
- 类选择器
<h2>Todo List</h2>
<ul>
<li class="done">Learn HTML</li>
<li class="done">Learn CSS</li>
<li>Learn JavaScript</li>
</ul>
<style>
.done {
color: gray;
text-decoration: line-through;
}
</style>
- 属性选择器
<label>用户名:</label>
<input value="zhao" disabled />
<label>密码:</label>
<input value="123456" type="password" />
<style>
[disabled] {
background: #eee;
color: #999;
}
</style>
伪类
伪类是不基于标签和属性定位元素的 有以下两种伪类
- 状态伪类(如下面的:link,visited,hover,active,focus等)
<a href="http://example.com">
example.com
</a>
<label>
用户名:
<input type="text">
</label>
<style>
a:link {
color: black;
}
a:visited {
color: gray;
}
a:hover {
color: orange;
}
a:active {
color: red;
}
:focus {
outline: 2px solid orange;
}
</style>
- 结构性伪类(如下面的:first-chaild,last-child等)
<ol>
<li>阿凡达</li>
<li>泰坦尼克号</li>
<li>星球大战:原力觉醒</li>
<li>复仇者联盟 3</li>
<li>侏罗纪世界</li>
</ol>
<style>
li {
list-style-position: inside;
border-bottom: 1px solid;
padding: 0.5em
}
li:first-child {
color: coral
}
li:last-child {
border-bottom: none;
}
</style>
组合(Combingators)
| 名称 | 语法 | 说明 | 示例 |
|---|---|---|---|
| 直接组合 | AB | 满足A同时满足B | input:focus |
| 后代组合 | A B | 选中B,如果它是A的子孙 | nav a |
| 亲子组合 | A>B | 选中B,如果它是A的子元素 | section>p |
| 兄弟选择器 | A,B | 选中B,如果它在A后且和A同级 | h2,p |
| 相邻选择器 | A+B | 选中B,如果它紧跟在A后面 | h2+p |
继承
某些属性会自动继承其夫元素的计算值,除非显示指定一个值。
<p>This is a <em>test</em> of <strong>inherit</strong></p>
<style>
body {
font-size: 20px;
}
p {
color: blue;
}
em {
color: red;
}
</style>
CSS求值过程
布局
- 确定内容的大小和位置的算法
- 依据元素、容器、兄弟节点和内容等信息来计算。
- 布局相关的技术有:
- 常规流
- 行级
- 块级
- 表格布局
- FlexBox
- Grid布局
- 浮动
- 绝对定位
- 常规流
块级VS行级
| Block Level Box | Inline Level Box |
|---|---|
| 不和其它盒子并列摆放 | 和其它行级盒子一起放在一行或拆开成多行 |
| 适用使用的盒模型属性 | 盒模型中的width、height不适用 |
| 块级元素 | 行级元素 |
|---|---|
| 生成块级盒子 | - 生成行级盒子 - 内容分散在多个行盒(line box)中 |
| body、article、div、main等 | span、em、strong、cite、code等 |
| display:block | display:inline |