Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Indent all tags following h2 until next h2 is hit using CSS

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.

like image 837
MKroehnert Avatar asked Aug 31 '25 01:08

MKroehnert


2 Answers

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.

like image 97
Quentin Avatar answered Sep 02 '25 17:09

Quentin


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).

like image 31
David Thomas Avatar answered Sep 02 '25 15:09

David Thomas