Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to center text in a div element?

Tags:

html

css

I'm trying to create square element, that will have text centered both vertically and horizontally. Additionally, the whole area of the square should be a link. This is my HTML:

<div class="w1h1 medium">
    <a class="userLink" target="_blank" href="Fancybox.aspx">
        <table style="width: 100%; height: 100%">
            <tr style="vertical-align: central">
                <td style="text-align: center; font-weight: bold;">
                    text in the middle 
                </td>
            </tr>
        </table>
    </a>
</div>

And this is my CSS:

div.w1h1 {
    width: 150px;
    height: 150px;
}

.medium {
    background-color: #06849b;
    color: white;
    font-family: sans-serif;
}

a.userLink
{
    width: 150px;
    height: 150px;
    display: table;
    color: #FFFFFF;
    text-decoration: none;
}

It works in Chrome and Firefox, but not in Internet Explorer. In IE the text is at the top of the square, not in the middle. Can you help me with this?

I just created playground here: http://jsfiddle.net/Tschareck/yfnnm/

like image 589
Tschareck Avatar asked Oct 09 '13 13:10

Tschareck


4 Answers

You could simplify your structure a bit, and use display:table-cell on the a element.

html

<div class="w1h1 medium">
    <a class="userLink" target="_blank" href="Fancybox.aspx">
       text in the middle 
    </a>
</div>

css

div.w1h1 {
    width: 150px;
    height: 150px;
    font-family:sans-serif;
    background-color: #06849b;
}
a.userLink {
    width: 150px;
    height: 150px;
    display: table-cell;
    vertical-align:middle;
    text-align:center;
    color: #FFFFFF;
    text-decoration: none;
}

Demo at http://jsfiddle.net/yWLYV/1/

works down to IE8

like image 183
Gabriele Petrioli Avatar answered Sep 24 '22 02:09

Gabriele Petrioli


A great way to get perfectly centered text is to use a flexbox layout. You can horizontally and vertically center the content of a container element with very little code:

.container-with-centered-content {
  display: flex;
  align-items: center;
  justify-content: center;
}

Demo: http://jsfiddle.net/913fch6v/

like image 36
bromy Avatar answered Sep 26 '22 02:09

bromy


Change <tr style="vertical-align: central"> to <tr style="vertical-align: middle"> and a.userLink property display to inline-block or inline.

jsfiddle

like image 36
Morpheus Avatar answered Sep 22 '22 02:09

Morpheus


try my technique; follow this

.outer{ float:left; width:100px; height:100px; background-color:#ccc; }
.innet{ float:left; width:100%; line-height:100px; text-align:center; }

<div class="outer">
        <span class="inner">This is my text</span>
</div>

and morpheus all right! ;)

like image 21
avalkab Avatar answered Sep 24 '22 02:09

avalkab