如何将一个 div 元素放置在另一个 div 元素的底部

3
我有两个div元素。我想了解如何完成以下操作:enter image description here 我有HTML和CSS代码:
    <div class="main">
      <div class="iner"></div>
    </div>

并且
.main{
  width: 1000px;
  height: 500px;
  background-color: #111210;

}

.iner{
  width: 250px;
  height: 250px;
  background-color: #34cb2f;
  margin: 0 auto;
  bottom: 0;
}

这段CSS代码可以让内部块居中显示,但是它会在顶部位置显示。如何将内部块放置在外部主块的底部,就像图片上一样呢?谢谢!
3个回答

8
  • position: relative;设置给父元素
  • position: absolute;bottom: 0;设置给子元素

.main{
  position:relative; /* ADD THIS! */
  height: 200px;
  background-color: #111210;
}

.iner{
  position:absolute; /* ADD THIS! */
  width: 100px;
  height: 100px;
  background-color: #34cb2f;
  bottom: 0;
  /* some horizontal centering now... */
  left: 0;
  right: 0;
  margin: 0 auto;
}
<div class="main">
  <div class="iner"></div>
</div>


由于其位置是绝对的,因此不需要边距。 - Joe Saad

3

使用弹性盒子布局:

.main {
  width: 1000px;
  height: 500px;
  background-color: #111210;
  display: flex;
  justify-content: center;
}

.inner {
  width: 250px;
  height: 250px;
  background-color: #34cb2f;
  align-self: flex-end;
}

https://jsbin.com/yuwubutiqi/


这可能是最好的解决方案,它不使用'相对'和'绝对'位置。 - Bishwajit Purkaystha

0
假设您的主要div宽度为500像素,内部div宽度为300像素。
 .main{
        width:500px;
        height:auto:margin:auto;
        background-color:green;
        border:1px solid #000000;
        min-height:500px;position:relative
        }

.inner{
        width:300px;
        height:auto;
        min-height:300px;
        background-color:yellow;
        position:absolute;
        bottom : 0;
        margin-right:100;
        margin-left:100px"
        }

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