简体   繁体   English

如何在div中水平居中表?

[英]How to horizontally center table inside div?

I have a <table> inside a <div> , with the styling below, the table is not being centered, why? 我在<div> <table>里面有一个<table> ,下面的样式,表没有居中,为什么?

Shouldn't everything within the <div> be formatted like I styled in the CSS? 不应该将<div>所有内容都格式化为我在CSS中设置的样式吗?

HTML HTML

<div> 
  <table></table> 
</div> 

CSS CSS

div{ 
  border: 5px solid white; 
  border-radius: 5px; 
  margin: auto; 
  text-align: center;
} 

You are setting margin: auto on the div, so the div will be centred … however you have also left the div as width: auto so it will be as wide its container (once you account for margins, padding and borders). 您在div上设置margin: auto ,因此div将居中...但是您还将div保留为width: auto因此它将与其容器一样宽(一旦考虑了边距,填充和边框)。

You are setting text-align: center on the div, so the inline children of the div will be centred, but the table is not inline, so it isn't affected (some of the table cells contents might be, depending on inheritance). 您在div上设置text-align: center ,因此div的内联子项将居中,但表不是内联的,因此它不受影响(某些表格单元格内容可能是,取决于继承) 。

If you want to centre the table then you have to centre the table itself. 如果您想使表居中,那么您必须将表本身居中。

table { margin: auto; }

The div element is block-level, and a block-level element occupies the entire space of its parent container, so margin: auto; div元素是块级的,块级元素占据其父容器的整个空间,因此margin: auto; does not take any effects by default. 默认情况下不会产生任何影响。 And text-align: center; text-align: center; works only for the inline-level children, but table is not one of them. 仅适用于内联级别的子级,但table不是其中之一。

You can set the table as inline table display: inline-table; 您可以将table设置为内联表display: inline-table; , so all the inline children including the table will be centered by text-align: center; ,所以包括表格在内的所有内联子项都将以text-align: center; on the parent div . 在父div

 div { border: 1px solid red; text-align: center; } table { border: 1px solid blue; display: inline-table; } 
 <div> <table> <tr> <td>Hello world</td> </tr> </table> </div> 

You might want to use 你可能想用

table{
    margin: auto;
}

Here is a fiddle : https://jsfiddle.net/7mhpv51s/1/ 这是一个小提琴: https//jsfiddle.net/7mhpv51s/1/

Just add margin to your table, as below. 只需在表格中添加保证金,如下所示。 When you use margin:auto for table it align your table to center of div . 当您对table使用margin:auto ,它会将您的tablediv center align Whereas when you use that on this <div> it will align that to center of browser . 而当你在这个<div>它时,它会将它与browser中心对齐。

table{
margin :auto;
}

And not to div, 而不是div,

div{
margin:auto /*No need over-here*/
}

try this: 尝试这个:

div{
width: 80%; /* try different value for this */
margin: auto;
}
table{
margin: auto;
}

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

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