-1

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

Val_
  • 331
  • 1
  • 3
  • 13

2 Answers2

0

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.

ATP
  • 2,939
  • 4
  • 13
  • 34
0

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;

Geo Daz
  • 214
  • 1
  • 11
  • I've added a margin-top:27px; to lower it in place just as in "wanted result" and it works great ! Thanks :) – Val_ Sep 21 '22 at 07:25
  • 1
    To add a bit more explication, left and top move top-left corner of the tag and % depends on parent sizes. To re-center child element from its top left corner, we use translate -50% that depends of its own sizes and make its center to the parent center. – Geo Daz Sep 21 '22 at 07:30
  • I reject the edit, because I answered to the title quesiton which is "vertically centered". – Geo Daz Sep 21 '22 at 07:34
  • 1
    I have edit now with that you really want I think @Val_ – Geo Daz Sep 21 '22 at 07:36