批改状态:合格
老师批语:估计现在会计算优先级了吧, 就是数数
必做: css 元素样式来源有哪些,实例演示
选做: css 优先级冲突的解决方案
(也就是浏览器自带的默认样式,比如字体颜色大小和边距)
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>h1 {color: rebeccapurple;}h2 {color: blue;}.meme {color: plum;}#love {color: red;}</style></head><body><h1>你好呀</h1><h2>hello</h2><p class="meme">么么哒</p><b id="love">爱你</b></body></html>注意:id > class类 > tag标签
<body><h1 style="font-style: oblique">你好呀</h1><h2 style="color: lightblue">hello</h2><p class="meme">么么哒</p><b id="love">爱你</b></body>
创建一个css文件,命名为style.css,内容如下:h1 {color: rebeccapurple;}h2 {color: blue;}.meme {color: plum;}#love {color: red;}
第一种方式(单个文件)
<style>@import url(style.css);</style>
第 2 种方式(多个文件,最常用)
<link rel="stylesheet" href="style.css" />
css 优先级排序
!important(强制展示)>行内元素>id 选择器>class 类选择器>tag 标签
选择器的优先级方案主要是解决 id 和 class 和 tag 的冲突
<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0" /><title>Document</title><style>/*0,0,1*/h2 {color: blue;}/*0,0,4*/html body h1 b {color: rebeccapurple;}/*0,1,0*/.meme {color: plum;}/*1,0,0*/#love {color: red;}/*1,0,4*/html body h1 b#love {color: green;}/*1,0,3*/body h1 b#love {color: yellow;}/*1,2,3*/body.min h1.meme b#love {color: palevioletred;}</style></head><body class="min"><h1 class="meme"><b id="love">爱你</b></h1></body></html>
总结:
最后显示颜色为 1,2,3 的 palevioletred。
示例中的 (body.min h1.meme b#love) 1,2,3 中 1 代表有一个 id,2 代表有一个 class,3 代表有三个 tag。
可以看成一个数字,数字越大优先级越高。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号