Home >Web Front-end >CSS Tutorial >Why Are My Inline Styles Being Overridden by My Stylesheet?

Why Are My Inline Styles Being Overridden by My Stylesheet?

Linda Hamilton
Linda HamiltonOriginal
2024-10-28 12:55:31978browse

Why Are My Inline Styles Being Overridden by My Stylesheet?

CSS Precedence: Why Inline Styles Are Overridden

In CSS, styles are applied to elements based on the precedence of their rules. When multiple rules target the same element, the one with the highest precedence will take effect.

In the provided example, you have an inline style that sets padding-left: 10px for td elements within a table with the rightcolumn ID. However, a style from a referenced stylesheet sets margin and padding to 0 for all elements within the .rightColumn class. The issue is that the styles from the referenced stylesheet have higher precedence, causing the inline styles to be overridden.

Calculating Specificity

CSS precedence is determined by the specificity of rules. Specificity is calculated based on the following criteria:

  1. Inline style declarations contribute 1 point to specificity (a = 1).
  2. Each ID in the selector contributes 10 points (b = n).
  3. Each class or pseudo-class in the selector contributes 1 point (c = n).
  4. Each element or pseudo-element in the selector contributes 1 point (d = n).

For example, a rule with the selector .rightColumn * has a specificity of 0010 (a = 0, b = 0, c = 1, d = 0), while a rule with the selector td has a specificity of 0001 (a = 0, b = 0, c = 0, d = 1). Since 0010 is greater than 0001, the rule from the referenced stylesheet has higher precedence.

Resolving the Issue

To resolve this issue and apply the inline styles, you have two options:

  1. Use !important: You can add !important to the inline style to force its higher importance. However, this approach can be difficult to maintain and should be avoided if possible.
  2. Increase rule specificity: You can add a more specific selector to the inline style to increase its specificity. For example, you could add a class name to the table cells and style them using a selector like .rightColumn .myUnpaddedTable. This way, the specificity of the inline style becomes 0011, which is higher than the specificity of the rule from the referenced stylesheet (0010).

The above is the detailed content of Why Are My Inline Styles Being Overridden by My Stylesheet?. 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