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

时间:2017-09-21 13:38:21

标签: html css css3 flexbox

当浏览器窗口在下面的代码中垂直缩小时,我需要避免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在真实场景中充当页脚。提前谢谢!

2 个答案:

答案 0 :(得分:2)

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

在弹性列项目上设置margin-top: auto时,它会将其推送到父级的底部,您可以在更大的屏幕上看到它。

&#13;
&#13;
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;
&#13;
&#13;

如果他们在某个时刻需要缩小,使用此样本时红色div会这样做,其中高度固定为完整视口。

就像这样,绿色被赋予flex-shrink: 0,这可以防止它收缩并保持其设定高度。

&#13;
&#13;
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;
&#13;
&#13;

答案 1 :(得分:1)

您需要将position: relative;设置为父级,在本例中为body元素,它将解决问题。当父母的职位为relative且孩子的职位为absolute时,孩子将尊重父母,并将相对于父母定位:

&#13;
&#13;
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;
&#13;
&#13;