16

Can someone explain how I vertically align the text in <a> elements - so both text appears in the middle of the red box?

http://jsfiddle.net/WeKtX/

Here's my HTML:

<ul>
<li><a href="#">this is a link</a></li>
<li><a href="#">this is an even longer link</a></li>
</ul>

and my CSS:

li {list-style-type:none;margin:0;padding:0}
li a {width:100px;float:left;background:red;margin-right:20px;height:40px}

Many thanks for any pointers

Hashem Qolami
  • 97,268
  • 26
  • 150
  • 164
michaelmcgurk
  • 6,367
  • 23
  • 94
  • 190

1 Answers1

14

If you want to center the text horizontally then try:

text-align: center;

If you want to center the text vertically then try:

line-height: 40px; //Where 40px is the height of your parent element

Keep in mind, that when using line-height, it will only work on one line of text. If you want to do multiple lines of text then I'm afraid you have to specify a height to the text and then use position: absolute; on the text with position: relative; on the parent element.

For your multi-line example I'd try something like the following jsFiddle:

li {
    list-style-type:none;
    margin:0;
    padding:0;
    position: relative;
    height: 60px;
    width: 200px;
    display: block;
    background:red;
}

li a {
    width:100px;
    height:40px;
    position: absolute;
    top: 50%;
    margin-top: -20px;
}
cereallarceny
  • 4,913
  • 4
  • 39
  • 74