Horizontally center absolute positioned element below the center of another element

北城余情 提交于 2019-12-07 01:45:05

问题


How can I get an absolute positioned element to be centered below the center of another element?

Example of usage: A date-picker that opens/shows a new (absolutely positioned) element when clicked.

        .         <-- Center
      [ . ]       <-- Not absolutely positioned element, a button. Always displayed
  [     .     ]   <-- Absolutely positioned element. Visibility toggled by button

Edit: To make it clear, what I'm looking for is a simple way to make the center of the elements align.


回答1:


There are different ways to do this, but I found that the easiest one is to do the following to the abolute positioned element:

  top: 0;
  left: 50%;
  transform: translateX(-50%);

Using this method you do not need to know the size either of the elements.

How does it work?

The left: 50% places it at the middle of the ancestor element (here 100% is the size of the ancestor element). The transform: translateX(-50%) makes the center of the absolutely positioned element come where it's left corner would otherwise be (here 100% is the width of the absolutely positioned element).

To make this work it's also important that the parent element has the same width as the button. I've used a parent element to contain both the button and the aboslutely positioned element i so that top: 0 is directly below the button.

Simplified html:

<span class="container">
  <div class="button">Click Me!</div>
  <div class="relative">
    <div class="absolute">Absolute positioned</div>
  </div>
</span>

Simplified less/scss

.container {
  display: inline-block;

  .button { ... }

  .relative {
    position: relative;

    .absolute {
      position: absolute;

      top: 0;
      left: 50%;
      transform: translateX(-50%);
    }
  }
}

Fiddle: https://jsfiddle.net/y4p2L9af/1/




回答2:


Personaly i would use css you set the size of the object if it is in a container if your main element is 100 % the width of the container and the two sub items can be set to have margin 0 auto this will force them to the center of the container css EG: #container{ width: 100%; }

#Main{width:100%}

div span{
 display:block;
 width: 25px;
 margin:0 auto;
}

html EG

<div id="Container">
    <span id="Main"></span>
    <span class="centered"></span>
    <span class="centered" id="absolute"></span>
</div>

this is the simplest option i could think of hope it helps



来源:https://stackoverflow.com/questions/35723850/horizontally-center-absolute-positioned-element-below-the-center-of-another-elem

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!