CSS - successive indenting of siblings after headings

∥☆過路亽.° 提交于 2019-12-02 21:06:12

问题


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 ?


回答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?




回答2:


You can use the CSS text-indent property.

h2, h2 + * {
    text-indent: 50px;
}
h3, h3 + * {
    text-indent: 100px;
}



回答3:


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 ?



来源:https://stackoverflow.com/questions/31872535/css-successive-indenting-of-siblings-after-headings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!