CSS实现不同标题下元素差异化缩进的问题咨询
Why Your Current Code Fails
Your existing CSS uses the adjacent sibling combinator (+), which only targets the immediately following sibling element. That’s why only the first paragraph or list after h1/h2 gets indentation—subsequent elements revert to the default padding-left: 0.
CSS-Only Fixes (No HTML Changes)
Here are two reliable ways to apply consistent indentation to all elements under a heading until the next heading:
Option 1: Broad Browser Support (No :has())
This approach uses general sibling combinators (~) and negation (:not()) to target all relevant elements between headings, working in most modern browsers and even some older ones:
/* Default padding for paragraphs and lists */ p, ul { padding-left: 0; } /* Apply 1em indent to all p/ul after h1 (excluding those under subsequent h1/h2) */ h1 ~ p:not(h2 ~ p, h1 ~ h1 ~ p), h1 ~ ul:not(h2 ~ ul, h1 ~ h1 ~ ul) { padding-left: 1em; } /* Apply 2em indent to all p after h2 (excluding those under subsequent h1/h2) */ h2 ~ p:not(h1 ~ p, h2 ~ h2 ~ p) { padding-left: 2em; }
The :not() selector excludes elements that fall under a later heading, ensuring indentation only applies to content directly under the target heading.
Option 2: Clean Modern Solution (Using :has())
If you only need to support modern browsers (Chrome, Firefox, Safari 15.4+), the :has() pseudo-class simplifies the logic dramatically. It lets you target elements that sit between a heading and the next heading:
/* Default padding */ p, ul { padding-left: 0; } /* Indent all p/ul after h1 until the next h1 or h2 */ h1 ~ p:not(:has(~ h1, ~ h2)), h1 ~ ul:not(:has(~ h1, ~ h2)) { padding-left: 1em; } /* Indent all p after h2 until the next h1 or h2 */ h2 ~ p:not(:has(~ h1, ~ h2)) { padding-left: 2em; }
This reads almost like plain English: "select all paragraphs after h1 that don’t have an h1 or h2 coming after them."
Quick Tips
- If your content includes other heading levels (like
h3), just add them to the negation selectors (e.g.,:not(h1, h2, h3)). - Test with your specific content structure to ensure edge cases (like multiple lists or mixed elements) work as expected.
内容的提问来源于stack exchange,提问作者Ross Aylen

