1.CSS 基本语法
CSS 有选择器,然后我们可以在选择器里面添加装饰;
2.CSS 基本选择器
1.标签选择器;
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><style type="text/css"> p{ font-size:20px; color:yellow; }</style></head><body> <p>生活</p></body></html>
复制代码
这就是标签选择器,p 就是标签;
2.类别选择器;
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><style type="text/css"> .a{ font-size:20px; color:yellow; } .b{ font-size:30px; color:blue; }</style></head><body> <p class="a">生活</p> <p class="b">编程</p></body></html>
复制代码
运行结果:
可见,类别选择器可以重复使用,非常方便!
注意:这里的类选择器要注意命名规则;
必须是字母或者字母和下划线开头
最好不要用保留字,如 body、head……
不能出现除了下划线(_)或连字符(-)以为的符号
3.ID 选择器;
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><style type="text/css"> #p1{ font-size:20px; color:yellow; } #p2{ font-size:20px; color:blue; }</style></head><body> <p id="p1">生活</p> <p id="p2">编程</p></body></html>
复制代码
运行结果:
ID 选择器是只能一次性使用,而且每个标签里面的 ID 是不同的,用起来不太方便;
注意:这里的类选择器要注意命名规则;
必须是字母或者字母和下划线开头
最好不要用保留字,如 body、head……
不能出现除了下划线(_)或连字符(-)以为的符号
3.在 HTML 中引入 CSS 的方法
1.行内样式
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title></head><body> <!-- 直接写在标签里面 --> <p style="color:yellow;font-size:20px">行内样式</p></body></html>
复制代码
运行结果:
2.内嵌式
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><style type="text/css"> p{ font-size:20px; color:red; }</style></head><body> <p>内嵌式</p></body></html>
复制代码
3.链接式
链接式需要再写一个.css 文件,将各种 css 样式的东西都写在这个文件里面;
这是.html 文件:
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><!-- 这些是链接外部文件的固定写法 --><link href="index3.css" type="text/css" rel="stylesheet"></head><body> <p>链接式</p></body></html>
复制代码
这是.css 文件(注意.css 文件的名称要和.html 文件中链接的名称一致!):
@CHARSET "UTF-8";p{ font-size:20px; color:red;}
复制代码
运行结果:
4.几种方式的优先级比较
几种方法都有一定的优先级比较:
行内样式>链接式>内嵌式;
<!DOCTYPE html><html><head><meta charset="UTF-8"><title>Insert title here</title><!-- 这些是链接外部文件的固定写法 --><!-- 链接式 红色--><link href="index3.css" type="text/css" rel="stylesheet"><!-- 内嵌式 蓝色--><style> p{ font-size:20px; color:blue; }</style></head><body> <!-- 行内样式 黄色--> <p style="font-size:20px;color:yellow;">行内样式>链接式>内嵌式</p></body></html>
复制代码
运行结果:
我是【程序员的时光】,热爱技术分享,信仰终身学习,爱健身,会点厨艺的热血青年,我们下期再见!
评论