6

I am having problems getting text within a table to appear centered in IE.

In Firefox 2, 3 and Safari everything work fine, but for some reason, the text doesn't appear centered in IE 6 or 7.

I'm using:

h2 {
  font: 300 12px "Helvetica", serif; 
  text-align: center; 
  text-transform: uppercase;
}

I've also tried adding margin-left:auto;, margin-right:auto and position:relative;

to no avail.

SwiftArchitect
  • 43,382
  • 25
  • 129
  • 168
Shady Studios
  • 63
  • 1
  • 2
  • 4

6 Answers6

6

CSS text-align property should be declared on the parent element and not the element you are trying to center. IE uses text-align: center property to center text. Firefox uses margin: 0 auto and it has to be declared on the element you are trying to center.

<div style="text-align: center">
    <h2 style="margin: 0 auto">Some text</h2>
</div>
zengabor
  • 1,934
  • 3
  • 22
  • 26
Alex Achinfiev
  • 433
  • 4
  • 8
4

The table cell needs the text-align: center.

Neeraj Kumar
  • 739
  • 2
  • 16
  • 30
Mike Becatti
  • 2,013
  • 1
  • 14
  • 29
2

Might be a typo, but you are missing a semicolon here:

margin-left:auto; margin-right:auto position:relative;

Should be:

margin-left:auto; margin-right:auto; position:relative;

If that doesn't work, make sure the element you are trying to center the text on has some width. Try setting the width to 100% and see if anything changes.

dawnerd
  • 748
  • 4
  • 10
1

If you can/want to use flexbox, you can use the following as well.

display: flex;
justify-content: center;
align-items:center
Rahi.Shah
  • 1,159
  • 8
  • 20
0

The text-align: center should be sufficient, since you're centering the text inside a block element (h2) - adjusting the margins will change the position of the block, not the text.

I wonder if it's just that IE is having a dummy-spit at that font declaration you've got there?

nickf
  • 499,078
  • 194
  • 614
  • 709
0

Use text-align:center in the div/td that surrounds the h2.

<table style = "width:400px;border:solid 1px;">
    <tr>
        <td style = "text-align:center;"><h2>hi</h2></td>
    </tr>
</table>

edit: wow, stackoverflow's community is pretty fast!

1077
  • 1,208
  • 1
  • 10
  • 9