开发者

How to align text vertically?

What is the easi开发者_如何学Goest 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;
    ...
}


Try the vertical-align property:

http://www.w3schools.com/css/pr_pos_vertical-align.asp


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. */

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜