css 基本
2019-03-14 本文已影响0人
downhill6
css基本
在HTML中使用CSS(引入CSS)
内联(inline style attribute)
<head> 标签内的 <style> 标签
<link> 标签中的外联
样式优先级(从高到低)
!important
内联样式
<style> 中的样式
link 中的样式
选择器
没有选择器就没法确定样式的作用范围,毫无重点的加样式,最后只会是一锅粥。所以熟练使用选择器是必备技能。
核心选择器
-
.
(英文句点)- 类选择器,使用类名选择。可能是使用最多,也是最灵活的选择器了。
- 如:
- HTML:
<div class="red">Yo</div>
- CSS:
.red { ... }
-
.red
就是类选择器,由于类可以在页面中重复出现,它天生就拥有批量选择的能力。
-
- HTML:
-
#
(井号)- ID选择器,使用ID选择。
- 如:
- HTML:
<div id="logo">Yo</div>
- CSS
logo { ... }
-
#logo
就是ID选择器,由于ID不可以在页面中重复出现,它天生就拥有极高权重,也就是说如果类选择下定义的样式和ID选择器下定义的样式发生冲突后一定是ID选择器获胜。
-
- HTML:
-
div
(元素名称)- 元素选择器,直接使用元素名称选择。
- 如:
- HTML:
<div>Yo</div>
- CSS:
div { ... }
- 一般与
.
或#
结合使用。
- 一般与
- HTML:
核心选择方式
-
目标1 目标2 ...
(注意中间的空格)- 后代选择器,可以将选择范围缩小至前一个元素。
- 目标之间可以是任何层级的包含关系,如父子关系,爷孙关系,不适用于兄弟关系。
-
目标1 > 目标
(大于号)- 父子选择器,可以将范围缩小至儿子辈,但选不中孙子辈。
选择器优先级(从高到低)
!important
内联样式
id 选择器
class 选择器
元素选择器
核心属性
display (显示方式)
-
block
- 块,默认占整宽。
- 通常作为容器分割页面,一些元素默认显示为
block
,如<div>
或<p>
。
-
inline
- 行内,通常存在于块级元素中作为内容填充,如文章的文字,图标,链接。一些元素默认显示为
inline
,如<span>
或<a>
。
- 行内,通常存在于块级元素中作为内容填充,如文章的文字,图标,链接。一些元素默认显示为
-
inline-block
- 行内块。可设置宽高。
float (浮动)
- 注意:
- 浮动元素撞到父级元素的“内壁”或和其他浮动元素摞到一起时才会停止“移动”,如果父级元素的空间不够,它们就另起一行。
-
fixed
或absolute
元素不浮动。 -
inline-block
或inline
元素在浮动后会变成block
元素。 - 未指定宽度的
block
元素的宽度会根据其内容长度而动态变化。 - 一组“正常”的元素中如果有一个元素浮动会发生什么事情?
盒模型
content
padding
border
margin
position (元素定位)
static relative absolute fixed
非 static 元素可以用 top left bottom right 属性来设置坐标
relative 是相对定位,原位置仍然留有空间
absolute 完全绝对定位, 忽略其他所有东西, 往上浮动到非 static 的元素
fixed 基于 window 的绝对定位, 不随页面滚动改变