Home > Article > Web Front-end > Why Does My Inline Style Get Overridden by a Stylesheet?
CSS Specificity: Ruling the Styling Hierarchy
In the world of web development, understanding CSS precedence is crucial to effectively manage conflicting styles. Consider the following scenario: a webpage contains both inline styling and a referenced stylesheet, but the stylesheet appears to override the inline styling.
This precedence issue arises due to the concept of CSS specificity. CSS assigns a numerical value to each style declaration based on the length and specificity of its selector. The higher the value, the greater the specificity, and the more likely it is to override other styles.
In the given example, the CSS provided is as follows:
<style> td { padding-left:10px; } </style>
and
.rightColumn * {margin: 0; padding: 0;}
The inline style declaration for td has a specificity of 0001 (zero ID attributes, zero class or attribute selectors, and one element name). The stylesheet declaration for .rightColumn * has a specificity of 0010 (zero ID attributes, one class selector, zero attribute or pseudo-class selectors, and zero element names).
According to CSS specificity rules, the latter declaration has a higher specificity and therefore takes precedence, even though it comes earlier in the source order.
To overcome this issue, there are two options:
For example:
<style> .important-td { padding-left:10px; } </style>
or
<style> #specific-td { padding-left:10px; } </style>
Understanding CSS specificity is essential for effective web design and ensuring that the styles applied to your elements are as intended. By leveraging the concept of specificity, developers can prioritize styles and create the desired visual appearance for their web pages.
The above is the detailed content of Why Does My Inline Style Get Overridden by a Stylesheet?. For more information, please follow other related articles on the PHP Chinese website!