user656925
user656925

Reputation:

Is it possible to center text in a div both vertically and horizontally?

I mean by not using any other tags...just one tag and the CSS for it.

So

http://jsfiddle.net/EqTsu/

<style>
  #test{
      width: 100px;
      height: 100px;
      text-align: center;
      border: solid 1px #ff0000;
    }
</style>

<div id='test'>foo</div>

needs what to center vertically?

Per Answers Below

It needs

  display: table-cell;
  vertical-align: middle;

Upvotes: 2

Views: 145

Answers (3)

Josh Allen
Josh Allen

Reputation: 997

Here's a jsFiddle using your code:

http://jsfiddle.net/EqTsu/2/

Adding display: table-cell; will cause the element to be treated like a cell in a table, which then enables you to use the table formatting CSS vertical-align: middle;.

Upvotes: 1

KRyan
KRyan

Reputation: 7618

There's a sort of hack-ish work-around where you give the <div> the display: table-cell; property and then the vertical-align: middle; property, yes.

So the complete CSS would be:

#test{
  display: table-cell;
  vertical-align: middle;
  width: 100px;
  height: 100px;
  text-align: center;
  border: solid 1px #ff0000;
}

Also, external stylesheets are your friends.

Upvotes: 2

Related Questions