当浏览器窗口缩小时,页脚重叠内容



当浏览器窗口在以下代码中垂直缩小时,我需要避免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充当了页脚。预先感谢!

box上使用min-height,从bottom中删除绝对定位,并且两个div的高度都将保留。

margin-top: auto设置在Flex列项目上时,它将将其推到属于父的底部,您可以在较大的屏幕上看到。

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;  
}
<div id="box">
  <div id="top">
  </div>
  <div id="bottom">
  </div>
</div>


如果他们在某个时候需要缩小,则使用此样本,红色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;  
}
<div id="box">
  <div id="top">
  </div>
  <div id="bottom">
  </div>
</div>

您需要将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
}
<div id="box">
  <div id="top">
  </div>
  <div id="bottom">
  </div>
</div>

最新更新