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.
To center an element both vertically and horizontally: position: absolute; left: 0; right: 0; top: 0; bottom: 0; margin: auto; But if you would like to understand how I came to these solutions, read further for more explanation.
Use the "inline-block" value of the display property to display the inner <div> as an inline element as well as a block. Set the text-align property on the outer <div> element to center the inner one. This property only works on inline elements.
The easiest way how to center a single element vertically and horizontally is to make it a flex item and set its margin to auto : If you apply auto margins to a flex item, that item will automatically extend its specified margin to occupy the extra space in the flex container...
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.
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.
<span class="container">
<div class="button">Click Me!</div>
<div class="relative">
<div class="absolute">Absolute positioned</div>
</div>
</span>
.container {
display: inline-block;
.button { ... }
.relative {
position: relative;
.absolute {
position: absolute;
top: 0;
left: 50%;
transform: translateX(-50%);
}
}
}
Fiddle: https://jsfiddle.net/y4p2L9af/1/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With