HTML 元素位置 CSS

HTML element position with CSS

如果我有以下 HTML 片段

...
<fieldset>
  <div>above or below</div>
  <div>content</div>
</fieldset>
...

如何创建 CSS 以便 <div>above or below</div> 可以位于 <div>content</div> 的上方或下方,而无需添加重复标记且不影响文档流?

我尝试在 fieldset 上使用 position: relative;,然后在字段 div 上使用 position: absolute;,但该元素随后位于其下方的任何元素之上。

您有一个选择是使用 display: flexflex-direction 以便在视觉上颠倒两个元素的顺序:

fieldset {
display: flex;
flex-direction: column;
}

.below {
flex-direction: column-reverse;
}
<fieldset>
  <div>above or below</div>
  <div>content</div>
</fieldset>

<fieldset class="below">
  <div>above or below</div>
  <div>content</div>
</fieldset>

如果您需要向 fieldset 添加更多元素,您也可以使用 display: flexorder:

fieldset {
  display: flex;
  flex-direction: column;
}

.first {
  order: 1;
}

div {
  order: 2;
}
<fieldset>
  <div>above or below</div>
  <div>content</div>
  <div>other stuff</div>
  <div>other stuff</div>
</fieldset>

<fieldset>
  <div>above or below</div>
  <div class="first">content</div>
  <div>other stuff</div>
  <div>other stuff</div>
</fieldset>