1

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

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

1

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

Comments

0

Try the vertical-align property:

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

1 Comment

Vertical align usually doesnt work in the way you'd think. phrogz.net/css/vertical-align/index.html
0

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

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.