42

I am trying to make a link which has a height and a width of 200px. The text of the link shall be centered vertically and horizontally.

This is my CSS so far:

a:link.Kachel {
  width: 200px;
  height: 200px;
  margin: 0 auto;
  display: block;
  text-align: center;
  background: #383838;
  display: -webkit-box;
  display: -moz-box;
  display: box;
  -webkit-box-align: center;
  -moz-box-align: center;
  box-align: center;
}

and this the HTML-code:

<tr>
  <td>
    <a class="Kachel" href="#">Test</a>
  </td>
</tr>

The text is horizontally centered but not vertically.

Any idea how to get the text centered both horizontally and virtically?

Igor Ivancha
  • 3,231
  • 4
  • 28
  • 39
user1567896
  • 2,278
  • 2
  • 23
  • 43

6 Answers6

78

remove all that other nonsense, and just replace height with line-height

a:link.Kachel{
   width: 200px;
   line-height: 200px;
   display: block;
   text-align: center;
   background: #383838;
}

jsfiddle: http://jsfiddle.net/6jSFY/

Eric Goncalves
  • 4,955
  • 4
  • 31
  • 57
39

In CSS3, you can achieve this with a flexbox without any extra elements.

.link {
    display: flex;
    justify-content: center;
    align-items: center;
}
Kilves
  • 800
  • 6
  • 12
6

If the text is only on one line, you can use line-height:200px; - where the 200px is the same as the height value.

If the text is on multiple lines and will always be on the same number of multiple lines, you can use padding combined with line-height. Example with 2 lines:

line-height:20px;
padding-top:80px;

This way the two lines will take up a total of 40px and the padding top puts them perfectly in the middle. Note that you'd need to adjust the height accordingly.

JSFiddle example.

If there is more than one link and it will have any number of lines, you will need some accompanying JavaScript to fix the padding on each.

James Donnelly
  • 117,312
  • 30
  • 193
  • 198
3

If the number of rows (or the inner element height) is not known, there is another trick using display: table and vertical-align:

.wrapper{
    display: table;
}
.link{
    display: table-cell;
    vertical-align: middle;
}

Example

Full article with details

Strae
  • 17,313
  • 26
  • 89
  • 129
2

Small point to add. If you remove the underline (text-decoration: none;) then the text will not be perfectly centred vertically. Links leave space for the underline. To my knowledge there is no way to override this except to add little extra top padding.

user2784627
  • 171
  • 2
  • 3
0

Maybe using padding? Like:

padding-top: 50%;