1

this is my first time on Stack Overflow, though I have found a lot of solutions here. But I couldn't find an answer to this question. I made a div clickable by putting an <a href> around it and then inside the <div> tags I put the text. Here is the link to JSFiddle: http://jsfiddle.net/fw6HT/3/

I am sure that I am overlooking something really obvious, but I can't get the text to vertically align within the div.
I hope you guys will be able to help me out!
I also stand open to other suggestions as to how to do this in a better way.

3 Answers3

2

Here is the fiddle

div {
    background:red;
    top:50px;
    height:200px;
    width:200px;
    text-align:center;
    display:table-cell;
    vertical-align:middle;
}

or if you have one line text

div {
    background:red;
    top:50px;
    height:200px;
    width:200px;
    text-align:center;
    line-height:200px;
}

but first solution is the best and common one

Mehmet Eren Yener
  • 1,876
  • 1
  • 20
  • 32
2

You basically will want to either

  1. wrap the text in a DIV instead of a SPAN
  2. or give the span "display: block" so you can manage it like a div

and then follow the rules here: Vertical alignment of elements in a div

Community
  • 1
  • 1
Alien Life Form
  • 531
  • 1
  • 5
  • 15
0

For completeness' sake, there's one super simple way to vertically and horizontally align any element within another element: flexible box layout module. Doesn't matter if you don't know the exact size of the content, doesn't matter if the container has a dynamic height/width.

All you need* is these three:

display: flex;
justify-content: center;
align-items: center;

jsFiddle

*Of course, flexbox is a fairly new feature. It's not available on older IEs (well, not without a polyfill anyway) and it might require some browser prefixing too.

If you're not targeting older browsers and/or use something like Autoprefixer, flexbox is pretty damn awesome.

thykka
  • 481
  • 2
  • 9