缩进所有孩子

时间:2017-12-16 17:37:18

标签: html css

我不确定为什么这不符合我的预期:

HTML

<details>
  <summary>SomeObject</summary>
  <details>
    <summary>SomeObject</summary>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
  </details>
  <div>someField: [1,2,3]  </div>
</details>

CSS

details > * {
  margin-left: 10em;
}

我的期望是:

> SomeObject
  > SomeObject
    someField: 1
    someOther: "abc"
  someField: [1,2,3]

但我得到的是:

> SomeObject
  > SomeObject
  someField: 1
  someOther: "abc"
someField: [1,2,3]

我不明白,因为details > *是为了选择所有细节的孩子吗?因此,我应该将所有细节缩进,包括<div> someField: [1,2,3]</div> ......但是,在这种情况下,这不会因某种原因而受到影响......我无法解释原因。有什么想法吗?

&#13;
&#13;
details > * {
  margin-left: 10em;
}
&#13;
<details>
  <summary>SomeObject</summary>
  <details>
    <summary>SomeObject</summary>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
  </details>
  <div>someField: [1,2,3]  </div>
</details>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

margin相对于父母。第二个div元素中的details将继承其父级margin,并应用其他margin

考虑这个例子:

details>* {
  margin-left: 10em;
  background: yellow;
}

details {
  background: pink;
}

details details {
  background: rgba(0,0,0,.1);
}
<details>
  <summary>margin-left</summary>
  <details>
    <summary>margin-left + margin-left</summary>
    <div>margin-left + margin-left</div>
    <div>margin-left + margin-left</div>
  </details>
  <div>margin-left</div>
</details>

您需要应用额外的左边距,以便最后div根据需要对齐。定位div的好方法是only-of-type选择器。

例如

details>* {
  margin-left: 10em;
}

details div:only-of-type {
  margin-left: 20em;
}
<details>
  <summary>margin-left</summary>
  <details>
    <summary>margin-left + margin-left</summary>
    <div>margin-left + margin-left</div>
    <div>margin-left + margin-left</div>
  </details>
  <div>margin-left 20em</div>
</details>

根据评论更新

details>* {
  margin-left: 10em;
}

details> :first-child {
  margin-left: 0;
}
<details>
  <summary>SomeObject</summary>
  <details>
    <summary>SomeObject</summary>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
  </details>
  <div>someField: [1,2,3]  </div>
</details>

答案 1 :(得分:0)

使用此:

&#13;
&#13;
details>*{
  margin-left: 2em;
}
details div{
  margin-left: 4em;
}
&#13;
<details>
  <summary>SomeObject</summary>
  <div>someField: [1,2,3] </div>
  <details>
    <summary>SomeObject</summary>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
    <details>
    <summary>SomeObject</summary>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
  </details>
  </details>
</details>
&#13;
&#13;
&#13;

答案 2 :(得分:0)

我的朋友想出了这个:

details > *:not(summary){
  margin-left: 2em;
}
<details>
  <summary>SomeObject</summary>
  <details>
    <summary>SomeObject</summary>
    <details>
      <summary>SomeObject</summary>
      <div>someField: 1</div>
      <div>someOther: "abc"</div>
    </details>
    <div>someField: 1</div>
    <div>someOther: "abc"</div>
  </details>
  <div>someField: [1,2,3]  </div>
</details>

我喜欢它主要是因为我不必列出详细信息标记的子项的所有潜在标记。