“位置:底部”不适用于相对定位的按钮元素

新手上路,请多包涵

_目标_:将 button 元素固定到 main 元素的底部。我尝试将它的容器定位为相对定位,以便它粘在底部:

 /* POSITIONING NOT WORKING. I WANT THIS DIV FIXED TO BOTTOM OF PARENT */
.wrapper:nth-child( 4 ) {
  background-color: #bbb;
  position: relative;
  bottom: 0;
}

这根本不会移动 .wrapper div。想法?

 @import url( "https://necolas.github.io/normalize.css/latest/normalize.css" );
* {
  box-sizing: border-box;
}
main {
  background-color: #eee;
}
main, input {
  padding: 2%;
}
main input {
  width: 100%;
  margin: 5% 0;
  border: 0;
}
.clr-fix::after {
  content: "";
  display: block;
  clear: both;
}
.wrapper {
  width: 23%;
  margin: 1%;
  padding: 2%;
  background-color: #ddd;
  float: left;
}

/* POSITIONING NOT WORKING. I WANT THIS DIV FIXED TO BOTTOM OF PARENT */
.wrapper:nth-child( 4 ) {
  background-color: #bbb;
  position: relative;
  bottom: 0;
}
 <main class="clr-fix">

  <div class="wrapper">
    <input type="text" value="position:bottom">
    <input type="text">
    <input type="text">
    <input type="text">
  </div>

  <div class="wrapper">
    <input type="text">
    <input type="text" value="Isn't working">
    <input type="text">
    <input type="text">
  </div>

  <div class="wrapper">
    <input type="text">
    <input type="text">
    <input type="text" value="On 'A button'">
    <input type="text">
  </div>

  <div class="wrapper">
    <button>A button</button>
  </div>

</main>

原文由 sol acyon 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 275
2 个回答

相对定位是相对于元素已经定位的位置的变化。因此,如果 position: relative、bottom: 0(或 top:0、left:0、right:0 等)意味着将其留在当前位置。

如果你想让this定位到元素的底部,你需要让父元素position: relative,你想要固定到底部的元素: absolute (with bottom: 0)。绝对定位的元素将跳出 DOM 流,而是相对于它最近的相对父元素。

基本上你想要:

 .wrapper {
  position: relative;
}

.wrapper:nth-child(4){
  position: absolute;
  bottom: 0;
}

原文由 Adam Beck 发布,翻译遵循 CC BY-SA 3.0 许可协议

您的主要样式需要应用一个相对位置。如前所述,您不能使用相对定位来定位 bottom:0 。看看这是否适合你。

 main{
  background-color: #eee;
  position: relative;
}
.wrapper:nth-child(4) {
  background-color: #bbb;
  position: absolute;
  bottom: 8%;
  right: 1%;
}

原文由 Mdalz 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题