一、什么是css?
CSS 指层叠样式表 (Cascading Style Sheets),样式定义如何显示控制 HTML 元素,从而实现美化HTML网页。样式通常存储在样式表中,目的也是为了解决内容与表现分离的问题。多个样式定义可层叠为一,后者可以覆盖前者样式。
二、样式层叠次序
- 浏览器器缺省设置
- 外部样式表
- 内部样式表(位于 标签内部)
- 内联样式(在 HTML 元素内部)
可以通过提高权重级别打破规则
三、语法
选择器{属性:值;属性:值;属性:值;…}
最后的分号可写可不写
<style>
h3{color: red; font-size: 30px;}
</style>
四、css中的注释
通过/* */来注释
<!-- html注释-->
<style>
/* css中的注释*/
h3{color: red; font-size: 30px;}
li{color: green;font-size: 15px;}
</style>
五、css使用方式
有三种方式:
- 外部样式表(External style sheet):将css样式写入css文件中,然后再通过link标签或者导入css文件引入。
<!-- 方式一(常用)-->
<link rel="stylesheet" href="./css/my.css">
<!-- 方式二 -->
<style type="text/css">
@import "./css/my.css";
</style>
- 内部样式表(Internal style sheet):将样式写在style标签中。
<style>
li{color: green;}
</style>
3.内联样式(Inline style):直接将样式写在标签内的style属性中。
<li style="color: hotpink; font-size: 22px;">内联样式(Inline style)</li>
这三种样式他们的作用域不同,外部样式表不仅仅可用于当前网页,也可以多个网页共用。内部样式是对当前的网页有用,而内联样式是仅仅针对于此标签。
六、css常用选择器
- html选择器:直接用html标签的名字当作选择器。
/* html选择器 */
h3{color: red;}
- 类选择器:通过标签内定义的class属性值前加上 " . "当作选择器。
格式: .类名{样式…}
其他选择符名.类名{样式…}
/* 类选择器:1、li标签class属性为cc的采用此样式 2、凡是class属性为dd的标签采用此样式*/
li.cc{color: red;}
.dd{color: black;}
<!--class值中间用空格隔开,代表此便签拥有两个class的值 cc和dd-->
<li class = "cc dd" id="hid">外部样式表(External style sheet)</li>
<li class ="cc">内部样式表(Internal style sheet)</li>
- id选择器:通过标签内定义的id属性值前加上"#"当作选择器。id选择器比class选择器级别要高,而且id属性值是唯一的。
格式: #id名{样式…}
/* id选择器 :id属性值为hid的标签采用此样式*/
#id{font-size: 20px;}
/*选择符的优先级:从大到⼩ [ID选择符]->[class选择符]->[html选择符]->[html属性]
测试选择器的优先级
通过!important来提升优先级*/
#sid{color:greenyellow}
.sc{color:green;background-color:#ddd;}
span{color:red !important;font-size:22px;}
- 关联选择器(包含选择器):多个标签通过空格隔开,具有包含关系。
格式: 选择器1 选择器2 选择器3 …{样式…}
h1 p{color:red} /*只有h1标签中的p标签才采⽤用此样式*/
- 组合选择器:多个选择器通过逗号隔开。
格式:选择器1,选择器2,选择器3, …{样式…}
h1,h2,h3,h4,h5{color:blue;} /*h1、h2、h3、 h4和h5都采用此样式*/
- 伪类选择器:标签名:伪类名{样式…}
a:link {color: #FF0000; text-decoration: none} /* 未访问的链接 */
a:visited {color: #00FF00; text-decoration: none} /* 已访问的链接 */
a:hover {color: #FF00FF; text-decoration: underline} /* 鼠标在链接上 */
a:active {color: #0000FF; text-decoration: underline} /* 激活链接 */