1

I need to center an entire table in xHTML. The tags that work in HTML to do so do not necessarily work in xHTML, but the way to do it is not obvious (to me).

Works in HTML:

<div>
<table border="0" cellspacing="0" cellpadding="0" align="center" style="border-collapse:collapse; width:90%;">

Not working in xHTML:

<div>
<table border="0" cellspacing="0" cellpadding="0" style="align:center;border-collapse:collapse; width:90%;">

Using text-align:center instead changes the alignment of text within cells, rather than the alignment of the entire table on the page.

What is the correct method to center align a table in xHTML.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
zeeple
  • 5,509
  • 12
  • 43
  • 71
  • 2
    I think you're better off using the margins to center it. like, "margin:0px auto". That works WAY better. – durbnpoisn May 16 '16 at 21:00
  • If you're going to use CSS anyway, you should also convert `border`, `cellpadding` and `cellspacing`. By the way, `align` isn't a CSS property; you meant `text-align`. That won't work though; see durbnpoisn's comment. – Mr Lister May 17 '16 at 07:46

3 Answers3

3

Posting as answer. I think you're better off using the margins to center it. like:

margin:0px auto;

That works WAY better. Hope that helps!

durbnpoisn
  • 4,666
  • 2
  • 16
  • 30
  • If in fact the need is to center a table in an XHTML page, with emphasis on the "X", then this may be the better answer because it illustrates the CSS that would be used to do that. See http://stackoverflow.com/questions/2612483/whats-so-bad-about-in-line-css#answer-2612494, et alia. – RBV May 17 '16 at 19:35
3

One way to accomplish this is to use margins in the style attribute:

<table style="margin-left:auto; margin-right:auto">
0

Keep in mind that you're using CSS to change adjective/styling whereas (X)HTML concentrates on noun constructs (headers, images, paragraphs, etc). XHTML table is a noun, CSS margin and text-align are adjectives used to describe those nouns.

Also it's simpler to use a block/inline catch-all class:

.center {margin: auto; text-align: center;}
John
  • 1
  • 13
  • 98
  • 177