相对内的绝对定位 - 使用 bottom: 0 似乎不起作用

Absolute positioning inside relative - using bottom: 0 doesn't seem to work

我正在尝试相对于包含 div 的底部定位项目。对父元素使用 position: relative 然后对子元素使用 position: absolute 似乎按预期工作。 (我使用 this article 作为参考。)

我的问题是,当我更改时:

top: 0;

bottom: 0;

对于内部元素之一,它跳转到包含 div 的顶部。我想让它相对于灰色块的底部。

代码如下:

 .channeldiv {
      margin: 0px;
      position: relative;
      display: inline-block;
    }
    
    .channel_summary {
      position: absolute;
      top: 0px;
      right: 0px;
      width: 50px;
      height: 50px;
      background-color: gray;
    }
    
    .channel_wrap {
      position: relative;
    }
    
    .inner_pink {
      position: absolute;
      bottom: 0;
      right: 0;
      width: 100%;
      height: 30px;
      z-index: 3;
    }
    
    .inner_green {
      position: absolute;
      top: 0;
      right: 0;
      width: 100%;
      height: 30px;
      z-index: 3;
    }
    
    .big_background {
      height: 73px;
      width: 128px;
      background-color: orange;
    }
    
    .overlaytext {
      position: absolute;
      top: 0px;
      right: 0px;
      width: 100%;
      text-align: right;
      z-index: 3;
      background-color: black;
      color: lightgreen;
      font-family: monospace;
    }
    
    .trades_num {
      position: absolute;
      top: 0px;
      left: 0px;
      z-index: 3;
      background-color: black;
      color: lightgray;
    }
<div class="channeldiv">
      <div class="big_background">
        <div class="channel_summary">
          <div class="channel_wrap">
            <svg class="inner_green" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <rect id="rect1" width="100%" height="100%" fill="green" />
            </svg>
            <span class="overlaytext">+1.00</span>
          </div>
        </div>
        <span class="trades_num">1</span>
      </div>
    </div>
    
    <div class="channeldiv">
      <div class="big_background">
        <div class="channel_summary">
          <div class="channel_wrap">
            <svg class="inner_pink" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
            <rect id="rect1" width="100%" height="100%" fill="pink" />
            </svg>
            <span class="overlaytext">+1.00</span>
          </div>
        </div>
        <span class="trades_num">2</span>
      </div>
    </div>



   

这是 fiddle:https://jsfiddle.net/davemabe/h6cv7prs/

您不需要在channel_wrap class 中设置position: relative;,因为在这种情况下它会禁用其child 定位。这样做之后,它就如你所愿。

你建议的文章只是两个定位(绝对相对),而你想要做的是三重定位(绝对相对相对)这不会产生你期望的结果

事实上,如果你想像这样保持三倍,你至少需要提供 channel_wrap div,例如一个高度,这样它的 children 就会知道如何对他们父母的定位做出反应,只有这样他们才会知道他们应该 bottomed 到哪里。

有关 positioning and bottom 的更多信息 属性