CSS中,如何将一个div放在它的兄弟元素的顶部,而它在HTML中则在下面?

6ju8rftf  于 2023-03-24  发布在  其他
关注(0)|答案(3)|浏览(201)

我在其他div后面有一个div,这就是为什么它不在视图的顶部,但是我想把它放在顶部,而不改变它在HTML中的位置。
HTML就像:

<div class = "some other divs"></div>
<div class = "some other divs"></div>
<div class = "some other divs"></div>
<div class = "some other divs"></div>

<div class = "main div"></div>
rkue9o1l

rkue9o1l1#

你可以使用css的flexbox和它的order属性,像这样:

body{
 display:flex;
 flex-direction:column;
 gap:2rem
}
/* just to have som visuals */
div{
  background-color:black;
  height:50px;
}

.main{
 background-color:red;
 /* bring it to the top */
 order:-1
}
<div class = "some other divs"></div>
<div class = "some other divs"></div>
<div class = "some other divs"></div>
<div class = "some other divs"></div>

<div class = "main div"></div>
iqih9akk

iqih9akk2#

Youssouf Oumar的回答非常好!另一种方法是使用grid

.container{
  display: grid;
}
.container div{
  width: 100%;
  height: 50px;
  border: solid green 1px;
}
.main{
  border: solid red !important;
  grid-row: 1 / 2;
}
<div class="container">
<div class = "some other divs">Item1</div>
<div class = "some other divs">Item2</div>
<div class = "some other divs">Item3</div>
<div class = "some other divs">Item4</div>

<div class = "main div">Item5</div>
</div>
fv2wmkja

fv2wmkja3#

您可以使用css属性z-index:设置每个div的堆栈位置

相关问题