前端场 - 了解css |青训营笔记
这是我参与「第四届青训营」笔记创作活动的的第二天
css 简介
css是什么
- Cascading Style Sheets
- 用来定义页面元素的样式
- 设置字体和颜色
- 设置位置和大小
- 添加动画效果
在页面使用css的三种方式
<!-—外链-->
<link rel="stylesheet" href=" / assets/ style.css">
<!--嵌入-->
<style>
li { margin:0; list-style: none;}
p { margin: 1em 0;}
</ style>
<! --内联-->
<p style="margin : 1em 0">Example Content</p>
css的工作原理
选择器 Selector
- 找出页面中的元素,以便给他们设置样式
- 使用多种方式选择元素
- 按照标签名、类名或id按照属性
- 按照DOM树中的位置
几种常见的选择器介绍
一、通配选择器( * )
<body>
<h1>This is heading</h1>
<p>This is some paragraph.</p>
</body>
<style>
*{
color: red;
font-size: 20px;
}
</style>
二、标签选择器( labelname )
<body>
<h1>This is heading</h1>
<p>This is some paragraph.</p>
</body>
<style>
h1{
color: orange;
}
p{
color: gray;
font-size: 20px;
}
</style>
三、id选择器( #idname )
<body>
<h1 id="head">This is heading</h1>
<p>This is some paragraph.</p>
</body>
<style>
#head{
color: blue;
font-weight: bolder;
}
</style>
四、类选择器( .classname )
<body>
<h2>Todo List</h2>
<ul>
<li class="done">Learn HTML</li>
<li class="done">Learn CSS</li>
<li>Learn JavaScript</li>
</ul>
</body>
<style>
.done{
color: gray;
text-decoration: line-through;
}
</style>
五、属性选择器( .classname )
<body>
<label>用户名</label>
<input value="zhao" disabled/>
<label>密码:</label>
<input value="123456" type="password" />
</body>
<style>
[disabled]{
background: #eee;
color: #999;
}
</style>
伪类(pseudo-classes)
- 不基于标签和属性定位元素
- 状态伪类
- 结构性伪类
css属性值与计算
初始值
css中,每个属性都有一个初始值
- background-color 的初始值为transparent
- margin-left 的初始值为О 可以使用initial关键字显式重置为初始值
- background-color: initial
css求值过程
布局
- 确定内容的大小和位置的算法
- 依据元素、容器、兄弟节点和内容等信息来计算
相关技术
容器的四个区域
margin 外边距区
- 指定元素四个方向的外边距
- 取值可以是长度、百分数、auto
- 百分数相对于容器宽度
border 边框区
- 指定容器边框样式、粗细和颜色
padding 内边距
- 指定元素四个方向的内边距
- 百分数相对于容器宽度
- content 内容区
利用border绘制三角形
<body>
<div class="triangle"></div>
</body>
<style>
.triangle{
width: 0;
height: 0;
border-top: 100px solid red;
border-left: 100px solid orange;
border-right: 100px solid blue;
border-bottom: 100px solid purple;
}
</style>
width与height
width
- 指定content box宽度
- 取值为长度、百分数、auto
- auto由浏览器根据其它属性确定
- 百分数相对于容器的content box宽度 height
- 指定content box高度
- 取值为长度、百分数、auto
- auto取值由内容计算得来
- 百分数相对于容器的content box高度
- 容器有指定的高度时,百分数才生效
块级 vs 行级
块级
- Block Level Box
- 不和其它盒子并列摆放
- 适用所有的盒模型属性
- 块级元素
- 生成块级盒子
- -内容分散在多个行盒(line box)中
- span、em、strong、cite、code等
- display: block
行级
- Inline Level Box
- 和其它行级盒子一起放在一行或拆开成多行
- 盒模型中的width、height不适用
- 行级元素
- -生成行级盒子
- body、article、div、main、
- section、h1-6、p、ul、li等
- display: inline
行级排版上下文
- Inline Formatting Context (IFC)
- 只包含行级盒子的容器会创建一个IFC。IFC内的排版规则
- 盒子在一行内水平摆放·一行放不下时,换行显示
- text-align决定一行内盒子的水平对齐
- vertical-align决定一个盒子在行内的垂直对齐避开浮动(float)元素*
块级排版上下文
- Block Formatting Context(BFC)·某些容器会创建一个BFC
- 根元素
- 浮动、绝对定位、inline-block- Flex子项和Grid子项
- overflow值不是visible的块盒- display: flow-root;
BFC内的排版规则
- 盒子从上到下摆放
- 垂直margin合并
- BFC内盒子的margin不会与外面的合并
- BFC不会和浮动元素重叠
Flex Box
- 一种新的排版上下文
- 它可以控制子级盒子的:
- 摆放的流向(→ ← ↑ ↓)
- 摆放顺序
- 盒子宽度和高度
- 水平和垂直方向的对齐
- 是否允许折行