Indent all tags following h2 until next h2 is hit

2019-07-04 10:37发布

In our project I'd like to style our doxygen output differently. Currently the generated html looks like the following:

<html>
<body>
    <h1> Heading 1 </h1>

    <h2> Heading 2.1 </h2>
    <p> Paragraph 2.1.1 </p>
    <p> Paragraph 2.1.2 </p>
    <p> Paragraph 2.1.3 </p>

    <h2> Heading 2.2 </h2>
    <p> Paragraph 2.2.1 </p>
    <p> Paragraph 2.2.2 </p>
    <p> Paragraph 2.2.3 </p>
</body>
</html>

The <h2> is only styled with a font-size attribute and all <h2> and <p> tags are aligned on the left side of the document.

To let the content below any <h2> tag stand out visually I would like to indent the tags until the next <h2> tag.

What I tried so far is the following CSS rule:

h2 + * {
    margin-left: 10px;
}

The * is used since there are also other tags present besides <p> tags. However, this rule only indents the first paragraph following the <h2> tag and not all tags up to the next <h2> tag.

It should also be mentioned that the structure of the html can not be changed to wrap each section inside of a <div> for example.

2条回答
forever°为你锁心
2楼-- · 2019-07-04 11:15

There's a couple of options of varying complexity, the first is:

h2 ~ *:not(h2) {
    margin-left: 1em;
}

JS Fiddle demo.

This approach selects all following-sibling elements of an h2 that is not itself an h2.

The second is slightly simpler:

body {
    padding-left: 1em;
}

body h2 {
    margin-left: -1em;
}

JS Fiddle demo.

This approach does, essentially, mean that all content except the h2 will be indented; so it's not quite perfect for your use-case, but may be adaptable to your specific requirements).

查看更多
贼婆χ
3楼-- · 2019-07-04 11:33

It sounds like you want to indent all siblings after the first h2 except other h2s, in which case this should do the job:

h2 ~ *:not(h2) {
    margin-left: 10px;
}

See the general sibling combinator and the negation pseudo-class as well as a live demo on jsbin.

查看更多
登录 后发表回答