Youssouf Oumar的回答非常棒!另一种方法是使用来自
我在其他一些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>
您可以使用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>
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>
您可以使用css属性z-index:
设置每个div的堆栈位置