简体   繁体   中英

How to align text vertically?

What is the easiest way to align the text vertically here with CSS ?

<ul>
    <li>Hello</li>
    <li>Bye Bye</li>
    <li>Ciao</li>
</ul>

li {
    border: 1px solid black;
    width: 100px;
    height: 50px;
    margin-bottom: 20px;
    text-align: center;
}

If you have just one line of text, you can set the line-height to the same value as the height . This works for any element.

Hacky, but possibly the easiest way:

li {
    display: table-cell; 
    vertical-align: center;
}

You will need to add a background image in place of the list item bullet.

If you know you're always going to center a single line you could match height and line-height

li {
    ...
    height: 50px;
    line-height: 50px;
    ...
}

Putting a line-height and making a gap between text and the border is good. but this is not the best practice. because Line height is not for creating a margin or padding. It is for creating a gap between two text lines(gap between two lines of a paragraph).

So make your task is done, you have to put a margin or a padding. The better option is putting a margin( But this is not a alignment. Just putting a margin to top ). And also, put your text into a "p" tag or "span" tag( whatever a tag, which can use for wrap text ).

HTML code,

<ul>
    <li><span>Hello</span></li>
    <li><span>Bye Bye</span></li>
    <li><span>Ciao</span></li>
</ul>

CSS Code,

ul li span {
    margin-top: 5px;
}

If making verticaly align is must, Here is the code.

  ul li {
     position: relative;
  }

  ul li span {
      position: absolute;
      top: 50%;
      font-size: 12px; /* change this as your need. */
      line-height: 12px; /* keep this value same as font-size. */
      margin-top: -6px; /* half value from the font-size. */

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM