如何将一个div固定在另一个div的底部?

13

好的,这是父级div:

#left {
    width: 50%;
    height: 100%;
    background-color: #8FD1FE;
    float: left;
    opacity:0.75;
    filter:alpha(opacity=75);
    -webkit-transition: all .45s ease;  
    -moz-transition: all .45s ease; 
    transition: all .45s ease; }

而这是内部的div:

#reasons {
background-image:url('arrow1.png');
background-repeat: no-repeat;
height: 94px;
width: 400px;
margin: 0 auto 0 auto; }

我尝试了很多不同的方法,但似乎不能将第二个div居中并固定在第一个div的底部。

2个回答

37

首先,将外部的div设为布局父元素:

#left {
     /* ... */
     position: relative; /* anything but static */
     /* ... */
}

现在让我们将内部的div固定在底部:

#reasons {
    /* ... */
    position: absolute;
    bottom: 0;
    /* ... */
}

现在它被固定在底部,但是我们需要将其居中:

#reasons {
    /* ... */
    left: 50%;
    margin: 0 0 0 -200px; /* 200px is half of the width */
    /* ... */
}

在 JSFiddle 上查看演示


3
你还可以考虑使用 transform: translateX(-50%) 来使子 div 居中,这样做的好处是(如果我没记错的话),你不需要在子元素上硬编码设置宽度(在这种情况下为400像素)。 - BardiaD

0
使用 position: absolute; bottom: 0; 将其保持在 div 底部,还要别忘了在主 div 中添加第二个 div。

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