Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

flex align-items center is not centering

I have a code - https://codepen.io/anon/pen/MQjpBG

It's a simple list with a colored block and text in each li

I need the list to be vertical and the text and block to be vertically aligned.

I'm trying to do this with flex and align-items but the text and block never center exactly

Am I doing something wrong, is there a better way to do this.

.element{
  display: flex;
  list-style: none;

  &__item{
    display: flex;
    align-items: center;
    margin-right: 10px;

    &:last-of-type{
      margin-right: 0;
    }

    &-square{
      background: red;
      //display: block;
      display: inline-block;
      height: 20px;
      width: 20px;
    }

    &-text{
      font-weight: bold;
    }

  }

}

I want the block and text to fit like so.

enter image description here

The align-items: center; seems to do it but its slightly off, like

enter image description here

like image 990
ttmt Avatar asked Feb 06 '18 17:02

ttmt


2 Answers

There's nothing centering them (in your codepen).

Add this to your code:

.element{
    display: flex;
    justify-content: center; /* horizontal alignment */

.element__item {
    display: flex;           /* nested flex container */
    align-items: center;     /* vertical alignment */
}

revised codepen

like image 109
Michael Benjamin Avatar answered Sep 29 '22 20:09

Michael Benjamin


Unfortunately, it looks like the issue is a function of the font chosen. Different fonts will have different descender heights (e.g. the tail of a "g") as well as different positioning of the base line relative to the full text box, and it appears that some fonts will have these values set such that they may not be visually centered.

I modified your CodePen example and forcibly set the font-family of the first element to Arial while leaving the second as the default (on Firefox on macOS 10.15/Catalina), and the Arial version definitely looks much more vertically centered:

enter image description here

You may be able to fix this by changing the font used, but obviously this isn't a change that can be made lightly on a large codebase.

like image 34
Richard Xia Avatar answered Sep 29 '22 18:09

Richard Xia