search
HomeWeb Front-endFront-end Q&AWhat is the significance of css weight

What is the significance of css weight

Dec 09, 2021 pm 01:45 PM
cssWeights

CSS weight refers to the priority of the style, which determines how the CSS rules are parsed by the browser until they take effect; when two or more styles act on an element, the style with the higher weight will affect the element. Function, and with the same weight, the style written later will overwrite the style written earlier.

What is the significance of css weight

The operating environment of this tutorial: Windows 7 system, CSS3&&HTML5 version, Dell G3 computer.

CSS weight refers to the priority of the style. There are two or more styles that act on an element. The style with the higher weight acts on the element. If the weight is the same, the style written later will overwrite the previous one. Writing style.

  • The weight determines how your css rules are parsed by the browser until they take effect. "CSS weight is related to how your CSS rules are displayed."

  • When many rules are applied to a certain element, weight is a process that determines which rule takes effect, or the priority.

  • Each selector has its own weight. Each of your CSS rules contains a weight level. This level is calculated by weighting different selectors. Through weights, different styles will eventually be applied to your web pages.

  • If two selectors are applied to an element at the same time, the one with the higher weight will take effect.

Basic rules for weight

1. Same weight: The selector that appears later is the final rule (for example, if you write the same two Each style #content h1 {color:red} )

2. Different weights, the higher the weight value will take effect

3.! important (infinite) > Inline style (weight 1000) > id selector (weight 100) > class selector (10) = pseudo-class selector (10) = attribute selector (10) > element selector (1)>Universal selector (0)>Inherited style>Browser default style.

4. The sum of element selectors will never have as much weight as class selectors.

The selector may contain one or more calculation points related to the weight. If the calculated weight value is larger, the weight of the selector is considered to be higher

css Weight calculation

If multiple selectors of different types set styles for an object at the same time, how the object will display the final style is given below. A simple calculation method is given below. For regular selectors they all have a priority weighted value, as explained below.

  • Tag selector: Priority weighted value is 1.

  • Pseudo-element or pseudo-object selector: priority weighted value is 1.

  • Class selector: Priority weighted value is 10.

  • Attribute selector: Priority weighted value is 10.

  • ID selector: Priority weighted value is 100.

  • Other selectors: the priority weighting value is 0, such as wildcard selectors, etc.

Then, use the above weighted value number as a starting point to calculate the total weighted value of the selector in each style. The calculation rules are as follows:

  • Count the number of ID selectors in the selector, and then multiply by 100.

  • Count the number of class selectors in the selector, and then multiply it by 10.

  • Count the number of tag selectors in the selector, and then multiply it by 1.

Follow this method, and finally add up all the weighted values ​​to get the total weighted value of the current selector. Finally, based on the weighted value, decide which style has the higher priority.

For a composite selector that is composed of multiple selectors, first calculate the weighted value of each component selector separately, then add it up to get the total score of the current selector, and finally based on the selector's The higher the score, the higher the priority, and the style set by it will be applied.

If the scores are the same, the judgment will be based on the positional relationship, and the style close to the object should have high priority.

[Example] Use different compound selectors to set style attributes for the same element through inline styles, and compare it through priority rules to get the final style attribute value.

<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>CSS样式优先级</title>
<style type="text/css">
div{
    margin: 0 auto;  /*div居中*/
    text-align: center;  /*文本居中*/
}
.Cent{
    width: 400px;  /*设置宽度,否则居中看不见效果*/
    border: 1px dashed #CC0099;  /*类别选择器设置边框线*/
    padding: 10px 15px;  /*设置间距*/
}
#imp{border: 1px dashed #3366FF;  /*ID 选择器设置边框线*/ }
.Cent{ font-size: 14px;  /*类别选择器设置字体大小*/ }
.Cent p{
    font-size: 16px;  /*类别选择器和标记选择器一起设置字体大小*/
    font-weight: bold;  /*字体加粗*/
}
.Cent .duanluo {
    font-weight: normal;  /*两次类别选择器设置取消加粗效果*/
    line-height:1.5em;  /*段落行髙*/
    text-align:left;  /*文本左对齐*/
}
.Cent .duanluo span{ color:#009966;  /*复合选择器设置字体彦员色*/ }
#imp span{
    color: #669933;  /*ID选择器和标签选择器进行定义*/
    font-weight: bold;  /*字体加粗*/
    font-size:22px;  /*字体22像素,要比较的地方*/
}
span{ font-size: 30px important;  /*<span>标签使用优先级最高的 !important 命令*/ }
span{ font-size: 40px; ! important  /*错误手写 !important 命令的位置*/ }
</style>
</head>
<body>
<div class="Cent" id="imp">
    <p class="duanluo" id="DL"><span>CSS</span>(Cascading Style Sheet,可译为“层叠样式表”或“级联样式表”)是一组格式设置规则,用于控制 Web 页面的外观。通过使用 CSS 样式设置页面的格式,可将页面的内容与表现形式分离。页面内容存放在 HTML 文档中,而用于定义表现形式的 CSS 规则则存放在另一个文件中或 HTML 文档的某一部分,通常为文件头部分。将内容与表现形式分离,不仅可使维护站点的外观更加容易,而且还可以使 HTML 文档代码更加简练,缩短浏览器的加载时间。
</p>
</div>
</body>
</html>

The page effect is as shown below.

What is the significance of css weight

In the above example, check the browser effect and analyze the code step by step. What you need to pay attention to is when testing: when testing each step below, the following code needs to be deleted, so The browser displays the results multiple times, and the browser displays the results at each step.

Step 1

To achieve browser centering, set the element centering attribute margin: 0 auto; and the text centering attribute text-align:center; for the div tag.

div { margin: 0 auto; text-align: center; }
  • Step 2

Set the width of the Cent layer to 400 pixels. If there is no width setting, the centering on the browser will also be invalid. , then set the inner spacing in 4 directions, and finally set the 1 pixel color to a pink dotted border line.

.Cent{ width: 400px; border: 1px dashed #CC0099; padding:10px 15px; }
  • Step 3

通过 ID 值引用 Cent 层,定义 1 像素颜色为粉蓝色虚线边框线,根据前面介绍的优先级规则:类选择器 10 分、ID 选择器 100 分,最终边框线颜色为蓝色。

如果将类别选择器 Cent 层和 ID 选择器 #imp 定义的顺序颠倒过来(如下所示),最终结果依然是蓝色,其原因在于 ID 选择器优先级别高于类选择器。

.Cent{ width: 400px; border: 1px dashed #CC0099; padding: 10px 15px; }
#imp { border: 1px dashed #3366FF; }
  • 第 4 步

.Cent{ } 定义字体大小为 14 像素,而 .Cent p{} 定义字体大小为 16 像素。根据前面介绍的优先级规则:类选择器 10 分、标签选择器 1 分,那么 .Cent{ } 为 10 分、.Cent p{} = 10+1 = 11分,故最终结果为段落字体大小为 16 像素且字体加粗显示。

.Cent { font-size: 14px; }
.Cent p { font-size: 16px; font-weight: bold; }
  • 第 5 步

Cent 层中段落添加 class 名 duanluo,定义字体不再加粗显示、行高 1.5em、文本左对齐,上一步的加粗设置如果字体大小无效,则查看加粗结果,行高设置使用相对单位,这样可以避免字体大小的改变而影响原先段落文字之间的距离。

段落内的 标签设置字体颜色为 #009966,而通过 ID 值设置字体颜色为 #669933。根据前面介绍的优先级规则:类选择器 10 分、标签选择器 1 分、ID 选择器 100 分,故 .Cent .duanluo span 得分 = 10+10+1 = 21分,而 #imp span 得分 = 100+1 = 101 分,最终字体颜色为 #669933。

.Cent .duanluo { font-weight:normal; line-height:1.5em; text-align:left }
.Cent .duanluo span{ color: #009966; }
#imp span{ color:#669933; font-weight:bold; font-size:22px }
  • 第 6 步

在设置段落字体大小时,最终 .Cent p 设置的字体大小为浏览器显示结果:16像素,而通过 ID 选择器定义字体大小后,字体大小变为 22 像素。

这里通过 !important 命令将 字体大小设置为 30 像素,因 !important 命令权限无限大,即分数值较高,暂定值为 1000,故 #imp span 分数为 101,小于 !important 命令值 1000,最终结果为 30 像素。

若span{ font-size:30px !important; }和#imp span{ font-size:5Opx !important; }进行比较,根据前面介绍的优先级规则:ID 选择器 100 分、标签选择器 1 分、!important 命令值 1000,故 span{} 得分为 1000(内部属性中 !important)+1(标签选择器)= 1001 分,而 #imp span 得分为 1000(内部属性中 !important)+100(ID选择器)+1(标签选择器)= 1101 分。

针对 !important 命令进行一次错误的写法并定义字体大小为 40 像素,通过浏览器发现:!important 命令放置在声明语句与分号之间,否则无效。

.Cent p { font-size: 16px; }
#imp span{ color:#669933; font-weight:bold; font-size:22px }
span{ font-size: 30px !important; }
span { font-size: 40px; !important }  /*错误书写方法*/

(学习视频分享:css视频教程

The above is the detailed content of What is the significance of css weight. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
HTML and React's Integration: A Practical GuideHTML and React's Integration: A Practical GuideApr 21, 2025 am 12:16 AM

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React and HTML: Rendering Data and Handling EventsReact and HTML: Rendering Data and Handling EventsApr 20, 2025 am 12:21 AM

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

The Backend Connection: How React Interacts with ServersThe Backend Connection: How React Interacts with ServersApr 20, 2025 am 12:19 AM

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React: Focusing on the User Interface (Frontend)React: Focusing on the User Interface (Frontend)Apr 20, 2025 am 12:18 AM

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

React's Role: Frontend or Backend? Clarifying the DistinctionReact's Role: Frontend or Backend? Clarifying the DistinctionApr 20, 2025 am 12:15 AM

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React in the HTML: Building Interactive User InterfacesReact in the HTML: Building Interactive User InterfacesApr 20, 2025 am 12:05 AM

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React: The Foundation for Modern Frontend DevelopmentReact: The Foundation for Modern Frontend DevelopmentApr 19, 2025 am 12:23 AM

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

The Future of React: Trends and Innovations in Web DevelopmentThe Future of React: Trends and Innovations in Web DevelopmentApr 19, 2025 am 12:22 AM

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software