当浏览器窗口在下面的代码中垂直缩小时,我需要避免div的重叠:
`
<html>
<body>
<style>
#box {
display: flex;
flex-direction: column;
align-items: center;
}
#top {
background-color: red;
height: 560px;
width: 400px;
}
#bottom {
background-color: green;
height: 100px;
width: 400px;
position: absolute;
bottom: 0
}
</style>
<div id="box">
<div id="top">
</div>
<div id="bottom">
</div>
</div>
<body>
</html>
`
为什么div会重叠。有没有办法可以避免这种重叠并具有相同的初始结构?底部div在真实场景中充当页脚。提前谢谢!
答案 0 :(得分:2)
在min-height
上使用box
,从bottom
移除绝对定位,并保留div
的两个高度。
在弹性列项目上设置margin-top: auto
时,它会将其推送到父级的底部,您可以在更大的屏幕上看到它。
body {
margin: 0;
display: flex; /* IE bug fix */
}
#box {
flex-grow: 1; /* fill body's width */
display: flex;
flex-direction: column;
align-items: center;
min-height: 100vh;
}
#top {
background-color: red;
height: 560px;
width: 400px;
border: 1px solid black;
}
#bottom {
margin-top: auto; /* push it to the bottom on big screen */
background-color: green;
height: 100px;
width: 400px;
border: 1px solid black;
}
&#13;
<div id="box">
<div id="top">
</div>
<div id="bottom">
</div>
</div>
&#13;
如果他们在某个时刻需要缩小,使用此样本时红色div
会这样做,其中高度固定为完整视口。
就像这样,绿色被赋予flex-shrink: 0
,这可以防止它收缩并保持其设定高度。
html, body {
margin: 0;
}
#box {
display: flex;
flex-direction: column;
align-items: center;
height: 100vh;
}
#top {
background-color: red;
height: 560px;
width: 400px;
border: 1px solid black;
}
#bottom {
margin-top: auto;
flex-shrink: 0;
background-color: green;
height: 100px;
width: 400px;
border: 1px solid black;
}
&#13;
<div id="box">
<div id="top">
</div>
<div id="bottom">
</div>
</div>
&#13;
答案 1 :(得分:1)
您需要将position: relative;
设置为父级,在本例中为body
元素,它将解决问题。当父母的职位为relative
且孩子的职位为absolute
时,孩子将尊重父母,并将相对于父母定位:
body {
position: relative;
}
#box {
display: flex;
flex-direction: column;
align-items: center;
}
#top {
background-color: red;
height: 560px;
width: 400px;
}
#bottom {
background-color: green;
height: 100px;
width: 400px;
position: absolute;
bottom: 0
}
&#13;
<div id="box">
<div id="top">
</div>
<div id="bottom">
</div>
</div>
&#13;