将一个div定位在另一个div底部附近

105

我有一个外部div和内部div。我需要将内部div放置在外部div的底部。

外部div是弹性的(例如宽度为70%)。我还需要居中内部块。

如下图所示,这个描述的简单布局模型:

图片描述


高度也是弹性的吗?如果不是,您可以将内部框的 margin-top 设置为(outerBoxHeight - innerBoxHeight)。 - peirix
@peirix:是的,外部块的高度可能会改变,而我们并不知道它。 - Roman
4个回答

82

经测试,适用于Firefox 3、Chrome 1以及IE 6、7和8:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
                      "http://www.w3.org/TR/html4/strict.dtd">
<html><body>
<div style='background-color: yellow; width: 70%;
            height: 100px; position: relative;'>
    Outer
    <div style='background-color: green;
                position: absolute; left: 0; width: 100%; bottom: 0;'>
        <div style='background-color: magenta; width: 100px;
                    height: 30px; margin: 0 auto; text-align: center'>
            Inner
        </div>
    </div>
</div>
</body>
</html>

Live版本在这里:http://jsfiddle.net/RichieHindle/CresX/


谢谢,你的解决方案几乎正确。我只需要在绿色块的样式中添加“//margin-left: -40px”以适应IE。如果没有这个带有margin-left属性的hack,你的绿色块在IE7中会被左侧排列。有人能解释一下这40像素是从哪里来的吗? - Roman
IE7在单词“Outer”后水平定位绿色div。我已更新代码以指定“left: 0”。 - RichieHindle

13

你需要一个包裹底部元素的div来实现居中。

<style>
   /* making it look like your nice illustration */
   #outer { width: 300px; height: 200px; background: #f2f2cc; border: 1px solid #c0c0c0; }
   #inner { width: 50px; height: 40px; background: #ff0080; border: 1px solid #800000; }

   /* positioning the boxes correctly */
   #outer { position: relative; }
   #wrapper { position: absolute; bottom: 3px; width: 100%; }
   #inner { margin: 0 auto; }
</style>


<div id="outer">
   <div id="wrapper"><div id="inner"></div></div>
</div>

9

CSS3的Flexbox可以轻松实现底部定位。请查看Flexbox支持表格

HTML

<div class="outer">
  <div class="inner">
  </div>
</div>

CSS

.outer {
  display: flex;
  justify-content: center; /* Center content inside */
}
.inner {
  align-self: flex-end; /* At the bottom of the parent */
}

输出:

.outer {
  background: #F2F2CD;
  display: flex;
  width: 70%;
  height: 200px;
  border: 2px solid #C2C2C3;
  justify-content: center;
}
.inner {
  background: #FF0081;
  width: 75px;
  height: 50px;
  border: 2px solid #810000;
  align-self: flex-end;
}
<div class="outer">
  <div class="inner">
  </div>
</div>


5

适用于所有浏览器,包括ie6。

<style>
    #outer{
        width: 70%;
        background-color: #F2F2CC;
        border: 1px solid #C0C0C0;
        height: 500px;
        position: relative;
        text-align: center;
    }

    #inner{
        background-color: #FF0080;
        border: 1px solid black;
        width: 30px;
        height: 20px;

        /* Position at the bottom */
        position: relative;
        top: 95%;

        /* Center */
        margin: 0 auto;
        text-align: left;
    }
</style>

<div id="outer">
    <div id="inner">
    </div>
</div>

顶部95%并不等同于底部10像素。您希望内部框在屏幕调整大小时锚定在底部。 - user959690

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