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 ?
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?
You can use the CSS text-indent
property.
h2, h2 + * {
text-indent: 50px;
}
h3, h3 + * {
text-indent: 100px;
}
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 ?