11

I need to center text vertically and horizontally. Is there a simple way to do this for the following code?

<div style="display: block; height: 25px;">
    <span id="ctl_txt" style="background-color: rgb(255, 0, 0);">
        Basic
    </span>
</div>
personal_cloud
  • 3,943
  • 3
  • 28
  • 38
Rubin
  • 375
  • 2
  • 6
  • 12

2 Answers2

18

You can use the text-align property to center the text horizontally, and line-height equal to the div height to center inline elements vertically.

<div style="display: block; height: 25px; text-align:center; line-height:25px;">
    <span id="ctl_txt" style="background-color: rgb(255, 0, 0);">Basic</span>
</div>

Example here.

Jose Faeti
  • 12,126
  • 5
  • 38
  • 52
7

Another way to do this, different from @Jose, is to use

display:table; and display:table-cell

like this

div{
    display:table; 
    height:125px;  //JUST FOR SHOW
    width:125px;   //JUST FOR SHOW
}

span{
    background-color: rgb(255, 0, 0);
    display:table-cell;
    vertical-align:middle;
    text-align:center;
}

Then vertical-align:middle; and text-align:center; do the work.

Example: http://jsfiddle.net/jasongennaro/unfwL/1/

Jason Gennaro
  • 34,535
  • 8
  • 65
  • 86
  • 1
    True @anglimass. However, since the OP did not mention browser restrictions, I thought he could see this alternate approach ;-) – Jason Gennaro Sep 17 '11 at 11:46