将一个div定位在容器底部

3
我是一名有用的助手,以下是您需要翻译的内容:

我正在尝试将一个div设置为flex容器页面底部。

不知何故,我能够使用以下方法实现:

position:absolute;
bottom: 10px;

但是div元素会扩展到整个视口

我正在尝试将其修复为单个框。

请检查代码。你会明白的。

https://jsfiddle.net/v3v1z7pv/

#container {
  display: flex;
  height: 100vh;
  width: 100vw;
  flex-flow: row;
}
body {
  margin: 0px;
  padding: 0px;
}
.box {
  min-width: 300px;
  border: 1px solid black;
  background-color: red;
}
.whiteBox {
  bottom: 10px;
  width: 100%;
  height: 100px;
  background-color: white;
  position: absolute;
}
<div id="container">
  <div class="box">
    <div class="whiteBox">Whte box</div>
  </div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
  <div class="box">7</div>
  <div class="box">8</div>
  <div class="box">9</div>
</div>

3个回答

2

.box添加position:relative。这样,whitebox就会留在里面。

相对定位的页面元素让您可以控制绝对定位的子元素。

在此处查看更多信息:相对定位和绝对定位

#container
{
  display:flex;
  height:100vh;
  width:100vw;
  flex-flow: row;
}
body{
  margin:0px;
  padding:0px;
}
.box
{
  min-width:300px;
  border:1px solid black;
  background-color:red;
  position:relative;
}
.whiteBox
{
  bottom:10px;
width:100%;
height:100px;
background-color:white;
position: absolute;

}
<div id="container">
  <div class="box">
    <div class="whiteBox">Whte box</div>
  </div>
  <div class="box">2</div>
  <div class="box">3</div>
  <div class="box">4</div>
  <div class="box">5</div>
  <div class="box">6</div>
  <div class="box">7</div>
  <div class="box">8</div>
  <div class="box">9</div>

</div>


1
你缺少将.box元素设为position:relative。添加这个属性后,你应该能得到想要的结果 :)

1
如果必须使用定位,则需将position: relative添加到box类,使其成为绝对定位的whiteBox子元素的边界框(即最近定位祖先)。
否则,此任务不需要绝对定位。可以纯粹使用弹性属性完成此任务。使用此方法,whiteBox元素不会从文档流中移除。
.box {
    min-width: 300px;
    border: 1px solid black;
    background-color: red;
    display: flex;             /* NEW */
}

.whiteBox {
    /* bottom: 10px; */
    width: 100%;
    height: 100px;
    background-color: white;
    /* position: absolute; */
    align-self: flex-end;      /* NEW */
}

#container {
    display: flex;
    height: 100vh;
    width: 100vw;
    flex-flow: row;
}

body {
    margin: 0px;
    padding: 0px;
}

.box {
    min-width: 300px;
    border: 1px solid black;
    background-color: red;
    display: flex;             /* NEW */
}

.whiteBox {
    /* bottom: 10px; */
    width: 100%;
    height: 100px;
    background-color: white;
    /* position: absolute; */
    align-self: flex-end;      /* NEW */
}
<div id="container">
    <div class="box">
        <div class="whiteBox">Whte box</div>
    </div>
    <div class="box">2</div>
    <div class="box">3</div>
    <div class="box">4</div>
    <div class="box">5</div>
    <div class="box">6</div>
    <div class="box">7</div>
    <div class="box">8</div>
    <div class="box">9</div>
</div>

修订版fiddle


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接