search
HomeWeb Front-endCSS TutorialUnderstanding style priority in CSS: Explanation of CSS style priority order

This article introduces to you the css style priority and gives you an in-depth understanding of the order of css style priority.

Understanding style priority in CSS: Explanation of CSS style priority order

Have you ever been in a situation where you tried to apply a css style to an element, but it had no effect? The page seems to ignore the CSS you defined, but you may not be able to figure out why. Maybe you will! important or add inline styles as a last resort. But actually the problem you are having is probably one of css priority. (Recommended course: css video tutorial)

A better understanding of which css styles to use first can lead to a clearer and more organized way to write css code, so let’s take a look at controlling a given html Three css rules for elements:

css priority calculation

css inheritance

css cascading

Learning these rules will make Take your CSS development to the next level.

Priority Calculation

Imagine that your html contains a paragraph that has a type of "creature" applied to it. You also have the following two css rules:

p { font-size :12px }
p.bio { font-size :14px }

Do you want the text size in the paragraph to be 12px or 14px? In this case you can guess it will be 14px. The second line of css (p.bio) is more specific than your class="bio" paragraph. However, sometimes priorities are not easy to see.

For example, consider the following html and css

<div id = “sidebar” >
<p class = “bio” >文字在这里</ p>
</ div>
div p.bio { font-size :14px }
#sidebar p { font-size :12px }

At first glance, the first line of css may seem more specific, but in fact the second line above is more consistent with the paragraph's font size. why is that?

To answer this question, we need to consider priority rules.

Specificity is calculated by counting the various components of css and expressing them in the form (a, b, c, d). This will be clearer with an example, but first the components.

Element, pseudo-element: d = 1 - (0,0,0,1)

Class, pseudo-class, attribute: c = 1 - (0,0,1,0)

Id: b = 1 - (0,1,0,0)

Inline style: a = 1 - (1,0,0,0)

The id is more specific than the class rather than the element.

You can calculate the priority by calculating each of the above and adding 1 to a, b, c or d. It's also important to note that 0,0,1,0 is more specific than 0,0,0,15. Let's look at some examples to make the calculation clearer.

p: 1 element - (0,0,0,1)

div: 1 element - (0,0,0,1)

#sidebar :1 element, 1 id - (0,1,0,0)

div#sidebar: 1 element, 1 id - (0,1,0,1)

div#sidebar p: 2 elements, 1 id - (0,1,0,2)

div#sidebar p.bio: 2 elements, 1 class, 1 id - (0,1,1 ,2)

Let’s look at the above example again

div p.bio { font-size :14px }  - (0,0,1,2)
#sidebar p { font-size :12px }  - (0,1,0,1)

The second one has higher priority and therefore takes precedence.

One final point before we move forward. Importance trumps priority when you use it! When you mark the css attribute important, you override the priority rules etc.

div p.bio { font-size :14px !important }    
#sidebar p { font-size :12px }

means that the first line of css above takes precedence over the second line instead of the second one. ! important is still the specificity surrounding the basic rules that you should never need if you understand how the rules work.

Inheritance

The idea behind inheritance is relatively easy to understand. Elements inherit styles from their parent container. If the body tag is set to use color:red, then the text of all elements in the body will also be red unless otherwise specified.

However, not all css properties are inherited. For example, margins and padding are non-inherited properties. If you set margins or padding on a div, the paragraphs inside the div will not inherit the margins and padding you set on the div. The paragraph will use default browser margins and padding until you declare otherwise.

However, you can explicitly set properties to inherit styles from its parent container. For example, you could declare

p { margin :inherit ; 填充:继承 }

and your paragraph would inherit from its containing element.

Cascading

At the highest level, cascading controls all CSS priorities and works as follows.

1. Find all CSS declarations that apply to related elements and attributes.

2. Sort by origin and weight. Origin refers to the source of the declaration (author style, user style, browser default value), and weight refers to the importance of the declaration. (The author's weight is greater than the user's weight is greater than the default value. !important is more important than the normal declaration)

3. Calculate the priority

4. If two rules among all the above rules are the same, Then the last rule wins. CSS embedded in html always comes after the external stylesheet, regardless of the order in the html.

#3 above is probably what you need to pay attention to the most. With #2 just understand that your styles will override how users set up their browsers unless they set the rule to important.

Also realize that your styles will override browser defaults, but these defaults do exist and often cause cross-browser issues. Using a reset file like Eric Meyer's CSS Reset or Yahoo's YUI Reset CSS helps take default styles out of the equation.

Summarize

Hope the above helps clarify some of your CSS priority issues. Most of the time, if your styles conflict, the issue will come down to priorities. Sometimes you haven't declared some CSS, but an element behaves in a way you don't expect it may have inherited some CSS from the parent container or the browser's default styles.

The general rule of thumb when declaring CSS is to declare the attribute with the lowest priority for styling an element. For example, use #sidebar instead of div#sidebar. I admit to breaking this general rule far more than I should, but by using the minimum required precedence it will make it easier for you to override styles by declaring more specific ones.

If you use highest priority, you may run into problems later and find yourself having to add unnecessary HTML to be able to add more priorities, or you may find yourself not using it anymore! important or declare the style inline. Start with the smallest priority and add more only when needed.

The above is the detailed content of Understanding style priority in CSS: Explanation of CSS style priority order. 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
@keyframes vs CSS Transitions: What is the difference?@keyframes vs CSS Transitions: What is the difference?May 14, 2025 am 12:01 AM

@keyframesandCSSTransitionsdifferincomplexity:@keyframesallowsfordetailedanimationsequences,whileCSSTransitionshandlesimplestatechanges.UseCSSTransitionsforhovereffectslikebuttoncolorchanges,and@keyframesforintricateanimationslikerotatingspinners.

Using Pages CMS for Static Site Content ManagementUsing Pages CMS for Static Site Content ManagementMay 13, 2025 am 09:24 AM

I know, I know: there are a ton of content management system options available, and while I've tested several, none have really been the one, y'know? Weird pricing models, difficult customization, some even end up becoming a whole &

The Ultimate Guide to Linking CSS Files in HTMLThe Ultimate Guide to Linking CSS Files in HTMLMay 13, 2025 am 12:02 AM

Linking CSS files to HTML can be achieved by using elements in part of HTML. 1) Use tags to link local CSS files. 2) Multiple CSS files can be implemented by adding multiple tags. 3) External CSS files use absolute URL links, such as. 4) Ensure the correct use of file paths and CSS file loading order, and optimize performance can use CSS preprocessor to merge files.

CSS Flexbox vs Grid: a comprehensive reviewCSS Flexbox vs Grid: a comprehensive reviewMay 12, 2025 am 12:01 AM

Choosing Flexbox or Grid depends on the layout requirements: 1) Flexbox is suitable for one-dimensional layouts, such as navigation bar; 2) Grid is suitable for two-dimensional layouts, such as magazine layouts. The two can be used in the project to improve the layout effect.

How to Include CSS Files: Methods and Best PracticesHow to Include CSS Files: Methods and Best PracticesMay 11, 2025 am 12:02 AM

The best way to include CSS files is to use tags to introduce external CSS files in the HTML part. 1. Use tags to introduce external CSS files, such as. 2. For small adjustments, inline CSS can be used, but should be used with caution. 3. Large projects can use CSS preprocessors such as Sass or Less to import other CSS files through @import. 4. For performance, CSS files should be merged and CDN should be used, and compressed using tools such as CSSNano.

Flexbox vs Grid: should I learn them both?Flexbox vs Grid: should I learn them both?May 10, 2025 am 12:01 AM

Yes,youshouldlearnbothFlexboxandGrid.1)Flexboxisidealforone-dimensional,flexiblelayoutslikenavigationmenus.2)Gridexcelsintwo-dimensional,complexdesignssuchasmagazinelayouts.3)Combiningbothenhanceslayoutflexibilityandresponsiveness,allowingforstructur

Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)Orbital Mechanics (or How I Optimized a CSS Keyframes Animation)May 09, 2025 am 09:57 AM

What does it look like to refactor your own code? John Rhea picks apart an old CSS animation he wrote and walks through the thought process of optimizing it.

CSS Animations: Is it hard to create them?CSS Animations: Is it hard to create them?May 09, 2025 am 12:03 AM

CSSanimationsarenotinherentlyhardbutrequirepracticeandunderstandingofCSSpropertiesandtimingfunctions.1)Startwithsimpleanimationslikescalingabuttononhoverusingkeyframes.2)Useeasingfunctionslikecubic-bezierfornaturaleffects,suchasabounceanimation.3)For

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 Article

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.