理解 CSS | 青训营笔记

35 阅读4分钟

这是我参与「第五届青训营 」伴学笔记创作活动的第 2 天 因为本人之前已经学了一些CSS了, 所以这里总结一下常用的CSS

选择器

基础: 基础选择器(单个选择器组成):标签选择器、类选择器、id 选择器和通配符选择器
复合选择器:后代选择器、子选择器、并集选择器、相邻兄弟选择器、伪类选择器

1. 基础选择器

标签选择器 p{color: red;} 类选择器 .nav{color: red;} id选择器 #nav{color :red;} 通配符选择器 *{color:red;}

2. 复合选择器

后代 父级 子级 {} 子代 父级 > 子级 {} (只选最近的一级) 并集 元素1,元素2 { 样式声明 } 相邻兄弟 img + p { 样式声明 } img后面紧跟的p

3. 伪类选择器

动态伪类选择器 E:link:选择 未被访问 的超链接(超链接点击之前)

E:visited:选择 已被访问 的超链接(链接被访问过之后)

E:active:选择 已被激活 的超链接(鼠标按住不放, 即鼠标点击标签,但是不松手时)

E:hover : 选择 鼠标悬浮 的超链接(鼠标悬浮在超链接上)

UI元素状态伪类选择器

E:checked(选中状态伪类选择器):匹配被选中的单选按钮或复选按钮

E:enabled(启用状态伪类选择器 ):匹配所有启用的表单元素

E:disabled(不可用状态伪类选择器):匹配所有禁用的表单元素

UI元素状态伪类选择器主要是针对于HTML中的Form元素进行操作

IE6-8不支持":checked",":enabled",":disabled"这三种选择器

结构伪类选择器 E:fisrt-child :元素E是父元素的第一个子元素,等价于E:nth-child(1)

E:last-child :元素E是父元素的最后一个子元素,等价于E:nth-last-child(1)

E:root:元素E所在文档的根元素,等价于html标签选择器(在html文档中)

E F:nth-child(n):父元素E的第n个子元素 且是 F

E F:nth-last-child(n):选择父元素E的倒数第n个子元素 且是F

E:nth-of-type(n) :选择父元素内具有指定类型的第n个E元素

E:nth-last-of-type(n):选择父元素内具有指定类型的倒数第n个E元素

E:first-of-type:选择父元素内具有指定类型的第一个E元素,与E:nth-of-type(1)等同

E:last-of-type :选择父元素内具有指定类型的最后一个E元素,与E:nth-last-of-type(1)等同

参数:

1.整数值(1 || 2 || 3 || 4 || ...) 参数n的起始值为1,不是0,若要选中第一个元素nth-child(1)

2.表达式(2n+1 || -n+5 || ...)

为表达式时,n从0开始,表达式的值为0或小于0的时,不选择任何匹配的元素。

3.关键词(odd || even) (第一个子素的下标是 1)

E:only-child :选择父元素只包含一个子元素,且该子元素匹配E元素

E:only-of-type选择父元素只包含一个同类型子元素,且该子元素匹配E元素

E:empty: 选择没有子元素的元素,而且该元素也不包含任何文本节点

否定伪类选择器 E:not(F):匹配所有除元素F外的E元素

4. 伪元素选择器

::after 用于在被选元素的内容前面插入内容 ::before 用于在某个元素之后插入一些内容 ex.

/*在p之前插入内容*/
p::before{
	content:"内容:";
	color:#c06;
	font-size:20px;
	font-family:"微软雅黑";
	font-weight:bold;
}

::first-letter 向文本的首字母添加特殊样式 ::first-line 向文本的首行添加特殊样式

5. 属性选择器

input[type]	
选择具有type属性的input元素,例如< input type=“text”>
input[type][name]	
选择具有type和name属性的input元素,例如< input type=“text” name=“a”>
input[type = “radio”]	
选择type属性值为radio的input元素,例如< input type=“radio”>
input[class ~= “rad”]	
选择class属性值包含rad的input元素(rad必须是一个单词),
例如
< input class=“aa raddd”>匹配失败,
< input class=“aa rad dd”>匹配成功
input[class I= “radio”]	
选择class属性值以radio-开头的input元素或属性值为radio,
例如< input class=“radio-sf”>< input class=“radio”>,
而 < input class=“radio sf”>匹配失败
input[class ^= “radio”]	选择class属性值以radio开头的input元素,
例如 < input class=“radiosf”> ,而< input class=“ra diosf”>匹配失败
input[class $= “radio”]	
选择class属性值以radio结尾的input元素,例如< input class=“raadd adradio”>
input[class *= “radio”]	
选择class属性值包含radio的input元素,例如< input class=“raddradioadd”>

字体属性和文本属性

一、字体属性

1.1 font-family

1.2 font-size

1.3 font-weight

1.4 font-style

二、文本属性

2.1 color

2.2 text-align

元素内文本内容的水平对齐方式

2.3 text-decoration

可以给文本添加下划线、删除线、上划线

2.4 text-indent

第一行的缩进,通常是将段落的首行缩进

2.5 line-height

行间的距离(行高)