【问题标题】:'Position: bottom' not working on relatively positioned button element“位置:底部”不适用于相对定位的按钮元素
【发布时间】:2017-08-12 07:00:18
【问题描述】:

目标:将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>

【问题讨论】:

    标签: html css position css-position


    【解决方案1】:

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

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

    基本上是你想要的:

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

    【讨论】:

    • 值得注意的是,尽管这会将我的元素移到底部。一旦绝对定位,它默认被推到最左边。 leftright 值可用于将元素移回其水平位置,如@Novocent 的答案所示。
    【解决方案2】:

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

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

    【讨论】:

      【解决方案3】:

      要使第 4 个包装器粘在底部,您需要将 position: relative; 放在 main 上,并将 position: absolute 添加到第 4 个包装器。

      position: absolute; 元素相对于它最接近的父元素(position: relative;)绝对定位 - 在您的情况下,这将是 main,它包装了第 4 个包装器。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多