Vertically center text in a 100% height div?

后端 未结 13 689
傲寒
傲寒 2020-12-05 17:22

I am working with a div that is 100% of the parent divs height.

The div only contains a single line of text.

The div cannot have a fixed height.

So m

13条回答
  •  被撕碎了的回忆
    2020-12-05 17:37

    The best and easiest way to do it (currently in 2015 2020) is using flexbox:

    .parent-selector {
        display: flex;
        align-items: center;
    }
    

    And that's it :D

    Check-out this working example:

    div {
        border: 1px solid red;
        height: 150px;
        width: 350px;
        justify-content: center;
    
        /* Actual code */
        display: flex;
        align-items: center;
    }

    Hola

    Old answer: You can use vertical-align: middle if you specify also display: table-cell;

    .div {
        display: table-cell;
        vertical-align: middle;
    }
    

    Working example:

    div {
      border: 1px solid red;
      height: 150px;
      width: 350px;
      text-align: center;
      
      /* Actual code */
      display: table-cell;
      vertical-align: middle;
    }

    Hola

    If it does not work you can try setting its parent as display: table;:

    .parent-selector {
        display: table;
    }
    

    Edit: You have this method plus all the methods covered on this question in this other question: How do I vertically center text with CSS?

提交回复
热议问题