blog/docs/code/html/css-weight.md

71 lines
1.5 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

---
title: CSS权重
date: 2022-01-09 00:38:02
tags:
- CSS
categories: CSS
author: Anges黎梦
---
CSS权重指的是样式的优先级有两条或多条样式作用于一个元素权重高的那条样式对元素起作用,权重相同的,后写的样式会覆盖前面写的样式。
## 权重的等级
可以把样式的应用方式分为几个等级,按照等级来计算权重
1、!important加在样式属性值后权重值为 10000
2、内联样式style=””权重值为1000
3、ID选择器#content权重值为100
4、类伪类.content、:hover 权重值为10
5、标签选择器div、p 权重值为1
## 权重的计算实例
### 1、实例一
```html
<style type="text/css">
div{
color:red !important;
}
</style>
......
<div style="color:blue">这是一个div元素</div>
<!-- 两条样式同时作用一个div上面的样式权重值为10000+1下面的行间样式的权重值为1000
所以文字的最终颜色为red -->
```
### 2、实例二
```html
<style type="text/css">
#content div.main_content h2{
color:red;
}
#content .main_content h2{
color:blue;
}
</style>
......
<div id="content">
<div class="main_content">
<h2>这是一个h2标题</h2>
</div>
</div>
<!--
第一条样式的权重计算: 100+1+10+1结果为112
第二条样式的权重计算: 100+10+1结果为111
h2标题的最终颜色为red
-->
```