使用CSS将按钮对齐到div底部

144

我想将我的按钮对齐到div的右下角。我该怎么做?

在这里输入图片描述

div的当前CSS:

    float: right;
    width: 83%;
    margin-right: 0px;
    font-family: Arial, Helvetica, sans-serif;
    font-size: 12px;
    height:625px;
    overflow:auto;
6个回答

292
您可以使用position:absolute;将元素绝对定位到父div中。当使用position:absolute;时,如果元素找不到已定位的父div,则它将从窗口位置进行绝对定位,因此您需要确保内容div已被定位。
要使内容div定位,所有非静态position值都可以工作,但relative最容易使用,因为它本身不会改变div的定位。
因此,在内容div中添加position:relative;,从按钮中删除浮动,并向按钮添加以下CSS即可:
position: absolute;
right:    0;
bottom:   0;

1
@Harry Joy:你是否也将position: relative应用于包含表单和按钮的元素? - thirtydot
1
@Harry Joy:那么它应该是相对于那个div而不是页面的。如果页脚也包含在这个div中,也许它们只是看起来一样。如果您知道页脚的高度,在按钮上可以使用bottom: HEIGHT_OF_FOOTERpx - thirtydot
1
@Harry Joy:这里有太多混乱了。你应该将你的HTML/CSS发布为jsFiddle测试用例 - thirtydot
1
@thirtydot:搞定了,谢谢。我把position:relative放错位置了,加在了错误的div里面。 - Harry Joy
3
我只是想留下评论并真诚地指出我有多开心能找到这个解决方案。这个问题困扰了我好几年! - K. Kilian Lindberg
显示剩余4条评论

67

CSS3 flexbox也可以用于将按钮对齐到父元素底部。

所需HTML:

<div class="container">
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>

必要的CSS:

.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}

截图:

输出图片

有用的资源:

* {box-sizing: border-box;}
body {
  background: linear-gradient(orange, yellow);
  font: 14px/18px Arial, sans-serif;
  margin: 0;
}
.container {
  justify-content: space-between;
  flex-direction: column;
  height: 100vh;
  display: flex;
  padding: 10px;
}
.container .btn-holder {
  justify-content: flex-end;
  display: flex;
}
.container .btn-holder button {
  padding: 10px 25px;
  background: blue;
  font-size: 16px;
  border: none;
  color: #fff;
}
<div class="container">
  <p>Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... Lorem ip sum dolor sit amet... </p>
  <div class="btn-holder">
    <button type="button">Click</button>
  </div>
</div>


18

父容器必须具备这个属性:

position: relative;

按钮本身必须具备以下特点:

position: relative;
bottom: 20px;
right: 20px;

或者任何你喜欢的东西


3
请注意,这个答案是错误的。使用 position:relative 属性会使按钮相对于其原始位置移动,而不是相对于其父元素移动。 - Kokos
4
为了将其放置在右下角,您需要使用 position: absolute - CaptainBli
1
父组件必须具有相对标签,而按钮应具有绝对标签。感谢@CaptainBli。 - maverick

4
我已经使用固定位置的方法解决了这个问题:
.button-corner {
  position: fixed;
  bottom: 20px;
  right: 20px;
}

0
在我的情况下:
position: sticky;
bottom: 0;
right: 0;

-28

向右移动,同样可以用于向左

.yourComponent
{
   float: right;
   bottom: 0;
}

5
这只会将你的按钮右对齐,不是底部右对齐。 - Ruben
float: right会将您的按钮对齐到右侧,但bottom属性不起作用,bottom只适用于除static以外的其他定位方式。 - Kunal Tyagi

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