Home >Web Front-end >CSS Tutorial >How Does CSS Stylesheet Override Order Work?

How Does CSS Stylesheet Override Order Work?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-17 05:31:24342browse

How Does CSS Stylesheet Override Order Work?

CSS Stylesheet Override Order: Demystified

In an HTML header, multiple stylesheets can be referenced, raising questions about the order in which they take precedence. This article explores the cascading nature of CSS stylesheets to clarify how the overrides work.

In the provided example, the header includes references to "styles.css" and "master.css." The latter overrides the former as it appears later in the cascade. However, specificity also plays a role.

According to the CSS cascading rules, more specific rules override more general ones. Consider the following:

body { margin:10px; }

This rule applies a 10px margin to all elements. However, a more specific rule follows:

html, body:not(input="button") {
    margin: 0px;
    padding: 0px;
    border: 0px;
}

This rule overrides the previous one because it targets specific elements (html and body) and excludes input buttons. As this rule appears later in the cascade and is more specific, it takes precedence.

It is important to note that specificity is calculated based on factors such as the number of IDs, classes, and element names used in the selector. Additionally, the !important declaration can override all other rules.

By understanding the cascading nature and specificity of CSS stylesheets, developers can ensure that their designs render as intended. Reference the W3C specification (http://www.w3.org/TR/2011/REC-CSS2-20110607/cascade.html#cascade) for in-depth details on rule precedence.

The above is the detailed content of How Does CSS Stylesheet Override Order Work?. 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