How to vertically center an absolute child relative to his parent and move it starting from that point?

Viewed 32

I'm trying to have a button with an icon as its child, overlaping its parent (the button) and being vertically centered relative to it.

Here is the result i want to obtain : wanted result

The button is declared like this :

<button class="btn btn-outline-primary btn-stage" >DIR <i class="fa fa-chevron-circle-down indicator" aria-hidden="true"></i> </button>

And the CSS to obtain what I currently have is this :

.btn-stage {
    width: 100%;
    margin: 0 2px 0 2px;
    font-size: 19px;
    position: relative;
}

.indicator {
    position: absolute;
    font-size: 32px;
    top: 0;
    transform: translate(50%, 5%);
    left: 35%;
    color: #005bbb;
    opacity: 0;
    z-index: 1;
}

The problem with using transform is that depending on the size of the window the icon slides left or right and never ends up really in the middle: Too large exemple & Too small exemple

2 Answers

change

left: 35%;
transform: translate(50%, 5%);

to

transform: translate(-50%, 5%);
left: 50%;

Explainition: the percentage of the left property are relative to the width of the parent, and the transform percentage are relative to the element size itself.

To vertically center an element in absolute, you can do :

.indicator {
   position: absolute;
   top: 50%;
   left: 50%;
   transform: translate(-50%, -50%)
}

top + translateY() = vertically centering
left + translateX() = horizontally centering

To do what you really want, vertically center on parent bottom and not on parent center. You can do : top 100%; or bottom: 0;

Related