CSS - successive indenting of siblings after headings
Asked Answered
B

3

0

I am needing to indent all elements after headings to give a visual structured layout.

I have seen that this is possible in the this question :

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

However, I am unable to "reset" when going back a level.

To be more clear, I need to have progressive indents which cancel when moving back.

So

H1
    H2
    .....
    H2
    .....
        H3
        ....
    H2
    .....
H1
....

If possible, I would prefer to not use enclosing DIV's but rather pure CSS.

Is this possible ?

Borneol answered 7/8, 2015 at 8:1 Comment(1)
Can you create a fiddle and show us your code?Fey
M
1

Here is a code snippet for indenting. I hope I understand what you want correctly.

* {
  margin: 0;
}
h1 ~ *:not(h1) {
  margin-left: 1em;
}
h2 ~ *:not(h1):not(h2) {
  margin-left: 2em;
}
h3 ~ *:not(h1):not(h2):not(.h2):not(h3) {
  margin-left: 3em;
}
h4 ~ *:not(h1):not(h2):not(.h2):not(h3):not(.h3):not(h4) {
  margin-left: 4em;
}
<h1>H1</h1>
<h2>H2</h2>
<h2>H2</h2>
<p class="h2">test</p>
<h3>H3</h3>
<p class="h3">test</p>
<h4>H4</h4>
<p class="h4">test</p>
<h2>H2</h2>
<p class="h2">test</p>
<h1>H1</h1>
<h2>H2</h2>
<h2>H2</h2>
<h1>H1</h1>

UPD:

Oh, I see about other elements - sorry didn't get it. Maybe somehow like this?

Munt answered 7/8, 2015 at 8:25 Comment(2)
Thanks @Munt this is a good starting place. However, the sibling elements which are not H* elements get indented gradually but do not go back out as the H* level decreases.Borneol
@Borneol I updated answer - please check, hope it'll helpMunt
C
0

You can use the CSS text-indent property.

h2, h2 + * {
    text-indent: 50px;
}
h3, h3 + * {
    text-indent: 100px;
}
Cutaneous answered 7/8, 2015 at 8:11 Comment(0)
B
0

Ok, here is the solution which works for me :

h1 + *:not(h1)
{
    margin-left: 0em;
}

h2 + *:not(h2), h2
{
    margin-left: 20px;
}

h3 + *:not(h3), h3
{
    margin-left: 40px;
}

The key is to use the plus sign (+) as opposed to the tilde sign (~). Hope this helps others also.


Edit : Ok, spoke too soon. This will successfully indent and outdent, but only for the first sibling element. If there are multiple sibling elements, it will fail. Any ideas ?

Borneol answered 7/8, 2015 at 11:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.