Reputation: 51
<style>
.dropdown-menu-center {
left: 50% !important;
right: auto !important;
-- text-align: center !important;
transform: translate(-50%, 0) !important;
}
</style>
I'm trying to center the drilldown list for the dropdown button with bootstrap 4... can someone explain this style ? My understanding that translate uses x and y axis..why would left 50% be used ? why cant i just put translate(50%,0) to replace left ? or just used left 50% and right auto , wouldn't it be placed at center?
Upvotes: 2
Views: 13968
Reputation: 184
If you want place div in center of another, you must be use this equation: (DIV_A / 2) - (DIV_B / 2). DIV_A represent the container and DIV_B the content.
Its same for height property.
Your case is the same operation
left: 50%; // (DIV_A / 2)
transform: translate(-50%,0); // - ( DIV_B / 2 )
Upvotes: 0
Reputation: 42304
The right
property in your sample doesn't matter - ignore that for a moment.
The left: 50%
in your sample states that the element should be offset by 50%. This means that simply adding left: 50%
will place the left edge of .dropdown-menu-center
in the exact middle, with the center of the element being right of that (specifically, half of the page width
plus half of the element width
).
This is countered with transform: translate(-50%, 0);
, which moves the element left by 50% of its width
. Thus, combining this with left: 0
places the center of .dropdown-menu-center
in the exact center of the page.
However, it's critical to note that this will only work if you use either relative positioning or absolute positioning:
.dropdown-menu-center {
border: 1px solid black;
height: 100px;
width: 100px;
position: absolute;
left: 50%;
transform: translate(-50%, 0);
}
<div class="dropdown-menu-center"></div>
Hope this helps! :)
Upvotes: 2