简体   繁体   English

居中对齐 HTML 表格

[英]Center-align a HTML table

On a page I'm working on at the moment, I can't seem to be able to center a table with an image in the first row and two columns of text below it (the two columns shouldn't be more than the image's width) Here's the page : http://www.puzzles-et-jeux.com/fr/page/minipuzzles.html I spent a lot of time trying to solve this.在我目前正在处理的页面上,我似乎无法将第一行中的图像和下方两列文本的表格居中(这两列不应超过图像的宽度)这是页面: http ://www.puzzles-et-jeux.com/fr/page/minipuzzles.html 我花了很多时间试图解决这个问题。 I would like to keep it in HTML because I have to rush and also because I have to create 20 pages of the sort with different widths /+ layouts for each image.我想将它保存在 HTML 中,因为我必须赶时间,还因为我必须为每个图像创建 20 个具有不同宽度 /+ 布局的页面。

For your design, it is common practice to use divs rather than a table.对于您的设计,通常使用 div 而不是表格。 This way, your layout will be more maintainable and changeable through proper styling.这样,您的布局将通过适当的样式更易于维护和更改。 It does take some getting used to, but it will help you a ton in the long run and you will learn a lot about how styling works.确实需要一些时间来适应,但从长远来看,它会帮助你很多,你会学到很多关于造型如何工作的知识。 However, I will provide you with a solution to the problem at hand.但是,我将为您提供手头问题的解决方案。

In your stylesheets you have margins and padding set to 0 pixels.在您的样式表中,您将边距和填充设置为 0 像素。 This overrides your align="center" attribute.这会覆盖您的align="center"属性。 I would recommend taking these settings out of your CSS as you don't normally want all of your elements to be affected in this manner.我建议您将这些设置从您的 CSS 中取出,因为您通常不希望所有元素都以这种方式受到影响。 If you already know what's going on in the CSS, and you want to keep it that way, then you have to apply a style to your table to override the previous sets.如果您已经知道 CSS 中发生了什么,并且希望保持这种状态,那么您必须对表格应用样式以覆盖之前的设置。 You could either give the table a class or you can put the style inline with the HTML.您可以给表格一个class ,也可以将样式与 HTML 内联。 Here are the two options:以下是两个选项:

  1. With a class:有一个类:

    <table class="centerTable"></table>

In your style.css file you would have something like this:在您的 style.css 文件中,您将拥有如下内容:

.centerTable { margin: 0px auto; }
  1. Inline with your HTML:与您的 HTML 内联:

    <table style="margin: 0px auto;"></table>

If you decide to wipe out the margins and padding being set to 0px, then you can keep align="center" on your <td> tags for whatever column you wish to align.如果您决定消除设置为 0px 的边距和填充,那么您可以在<td>标记上为您希望对齐的任何列保留align="center"

table
{ 
margin-left: auto;
margin-right: auto;
}

This will definitely work.这肯定会奏效。 Cheers干杯

尝试这个 -

<table align="center" style="margin: 0px auto;"></table>

Give it a class of center给它一个中心

then on CSS然后在 CSS

.center {
  margin-left: auto;
  margin-right: auto;
}
      margin-left: auto;
    margin-right: auto;

You could adjust it depending on the screen size您可以根据屏幕大小进行调整

<table align="center"></table>

这对我有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM