How to align text vertically?

心不动则不痛 提交于 2019-12-02 07:13:53

问题


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;
}

回答1:


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.




回答2:


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.




回答3:


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;
    ...
}



回答4:


Try the vertical-align property:

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




回答5:


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

}


来源:https://stackoverflow.com/questions/2826681/how-to-align-text-vertically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!