Vertical align text in block element

后端 未结 9 938
盖世英雄少女心
盖世英雄少女心 2020-12-04 09:53

I know vertical alignment is always asked about, but I don\'t seem to be able to find a solution for this particular example. I\'d like the text centered within the element,

相关标签:
9条回答
  • 2020-12-04 10:56

    with thanks to Vlad's answer for inspiration; tested & working on IE11, FF49, Opera40, Chrome53

    li > a {
      height: 100px;
      width: 300px;
      display: table-cell;
      text-align: center; /* H align */
      vertical-align: middle;
    }
    

    centers in all directions nicely even with text wrapping, line breaks, images, etc.

    I got fancy and made a snippet

    li > a {
      height: 100px;
      width: 300px;
      display: table-cell;
      /*H align*/
      text-align: center;
      /*V align*/
      vertical-align: middle;
    }
    a.thin {
      width: 40px;
    }
    a.break {
      /*force text wrap, otherwise `width` is treated as `min-width` when encountering a long word*/
      word-break: break-all;
    }
    /*more css so you can see this easier*/
    
    li {
      display: inline-block;
    }
    li > a {
      padding: 10px;
      margin: 30px;
      background: aliceblue;
    }
    li > a:hover {
      padding: 10px;
      margin: 30px;
      background: aqua;
    }
    <li><a href="">My menu item</a>
    </li>
    <li><a href="">My menu <br> break item</a>
    </li>
    <li><a href="">My menu item that is really long and unweildly</a>
    </li>
    <li><a href="" class="thin">Good<br>Menu<br>Item</a>
    </li>
    <li><a href="" class="thin">Fantastically Menu Item</a>
    </li>
    <li><a href="" class="thin break">Fantastically Menu Item</a>
    </li>
    <br>
    note: if using "break-all" need to also use "&lt;br>" or suffer the consequences

    0 讨论(0)
  • 2020-12-04 10:57

    Would using padding be OK for your needs?: http://jsfiddle.net/sm8jy/:

    li {
        background: red;
        text-align:center;
    }
    li a {
        padding: 4em 0;
        display: block;
    }
    
    0 讨论(0)
  • 2020-12-04 10:59
    li a {
    width: 300px;
    height: 100px;
    display: table-cell;
    vertical-align: middle;
    margin: auto 0;
    background: red;
    

    }

    0 讨论(0)
提交回复
热议问题