【问题标题】:Center absolute div under its parent using percentages not absolute values使用百分比而不是绝对值在其父级下居中绝对 div
【发布时间】:2019-02-09 08:33:59
【问题描述】:

Thisthisthis 问题相似但没有帮助。

目标是使用百分比而不是绝对值在其父元素下方居中。这样,如果尺寸发生变化,位置值就不需要改变。

下面的hover 元素在outer 下方居中,但定位需要绝对值,这取决于hoverouter 的大小。如果其中任何一个发生更改,则位置值必须更改。

可以通过百分比实现在父级下方居中吗?

Codepen:https://codepen.io/anon/pen/dadjpg

<div id="outer">
  <div id="hover"></div>
</div>

#outer {
  width: 200px;
  height: 200px;
  background: blue;
  position: relative;
}

#hover {
  width: 50px;
  height: 50px;
  background: yellow;
  position: absolute;
  margin: auto;
  left: 75px;
  bottom: -50px;
}

【问题讨论】:

    标签: html css


    【解决方案1】:

    你也可以使用top:100%; left:0px; right:0px; margin:0px auto;

    #outer {
      width: 200px;
      height: 200px;
      background: blue;
      position: relative;
    }
    
    #hover {
      width: 50px;
      height: 50px;
      background: yellow;
      position: absolute;
      left:0px;
      right:0px;
      top:100%;
      margin:0px auto;
    }
    <div id="outer">
      <div id="hover"></div>
    </div>

    【讨论】:

      【解决方案2】:

      您可以使用top:100% 将元素移动到底部,然后简单地将left:50%translateX(-50%) 组合到中心:

      #outer {
        width: 200px;
        height: 200px;
        background: blue;
        position: relative;
      }
      
      #hover {
        width: 50px;
        height: 50px;
        background: yellow;
        position: absolute;
        left:50%;
        transform:translateX(-50%);
        top:100%;
      }
      <div id="outer">
        <div id="hover"></div>
      </div>

      考虑bottom:0的逻辑相同

      #outer {
        width: 200px;
        height: 200px;
        background: blue;
        position: relative;
      }
      
      #hover {
        width: 50px;
        height: 50px;
        background: yellow;
        position: absolute;
        bottom:0;
        left:50%;
        transform:translate(-50%,100%);
      }
      <div id="outer">
        <div id="hover"></div>
      </div>

      另一个想法是考虑让flexbox在元素内部居中,然后平移以使元素在外部:

      #outer {
        width: 200px;
        height: 200px;
        background: blue;
        position: relative;
        display:flex;
      }
      
      #hover {
        width: 50px;
        height: 50px;
        background: yellow;
        margin:auto auto 0;
        transform:translateY(100%);
      }
      <div id="outer">
        <div id="hover"></div>
      </div>

      【讨论】:

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