Html 如何在div内水平居中表格?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38293514/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to horizontally center table inside div?
提问by gte_
I have a <table>
inside a <div>
, with the styling below, the table is not being centered, why?
我有一个<table>
里面 a <div>
,下面的样式,桌子没有居中,为什么?
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;
}
回答by Quentin
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).
您margin: auto
在 div上设置,因此 div 将居中……但是您也离开了 div,width: auto
因此它与容器的宽度相同(一旦考虑了边距、填充和边框)。
You are setting text-align: center
on the div, so the inlinechildren 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).
您正在text-align: center
div上设置,因此 div 的内联子项将居中,但表格不是内联的,因此不受影响(某些表格单元格内容可能会受到影响,具体取决于继承)。
If you want to centre the table then you have to centre the table itself.
如果要使表格居中,则必须将表格本身居中。
table { margin: auto; }
回答by Stickers
The div
element is block-level, and a block-level element occupies the entire space of its parent container, so margin: auto;
does not take any effects by default. And text-align: center;
works only for the inline-level children, but table
is not one of them.
所述div
元件是块级,和一个块级元素占据其父容器的整个空间,因此margin: auto;
不采取默认的任何效果。并且text-align: center;
仅适用于内联级别的孩子,但table
不是其中之一。
You can set the table
as inline table display: inline-table;
, so all the inline children including the table will be centered by text-align: center;
on the parent div
.
您可以将table
内联表设置为内联表display: inline-table;
,因此包括表在内的所有内联子项都将以text-align: center;
父项为中心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>
回答by Cephou
You might want to use
你可能想用
table{
margin: auto;
}
Here is a fiddle : https://jsfiddle.net/7mhpv51s/1/
这是一个小提琴:https: //jsfiddle.net/7mhpv51s/1/
回答by frnt
Just add margin to your table, as below. When you use margin:auto
for table
it align
your table
to center
of div
. Whereas when you use that on this <div>
it will align that to center of browser
.
只需在表格中添加边距,如下所示。当你使用margin:auto
了table
它align
你table
要center
的div
。而当你使用它时,<div>
它会将它与browser
.
table{
margin :auto;
}
And not to div,
而不是 div,
div{
margin:auto /*No need over-here*/
}
回答by Abk
try this:
尝试这个:
div{
width: 80%; /* try different value for this */
margin: auto;
}
table{
margin: auto;
}