简体   繁体   English

如何在div中将表格元素居中?

[英]How to center a table element within a div?

Please take a look at this fiddle: 请看一下这个小提琴:

(This question is not the same as the one I asked yesterday. Today, I need to center the innerTable within a div, not within a td element.) (这个问题与我昨天问的问题不同。今天,我需要将innerTable放在div的中心,而不是td元素的中心。)

https://jsfiddle.net/dve3413/rxdhcsvc/51/ https://jsfiddle.net/dve3413/rxdhcsvc/51/

I'm trying to get 'innertable' to be centered in 'tddiv'. 我试图使“内在”集中在“ tddiv”中。 The overflow should be equal on both sides of 'tddiv'. “ tddiv”的两侧的溢出应该相等。 'innertable' should be horizontally centered and vertical align on top. “内部”应水平居中,垂直对齐在顶部。 The overflow should also be centered (equal on left and right). 溢出也应居中(左右相等)。 The overflow vertically should all go down. 垂直方向的溢流应全部减少。 Ideally, css to accomplish this can be contained within 'tddiv' and 'innerTable'. 理想情况下,可以在'tddiv'和'innerTable'中包含用于实现此目的的CSS。

<table class="outerTable" align="center" border=1>
  <tr>
    <td valign=top>
      <div class="tddiv">
        <table class="innerTable" width=300px height=300px border=1 align=center>
        </table>
      </div>
    </td>
  </tr>
</table>

.outerTable {
  table-layout: fixed;
  /*   overflow: hidden; */
}

.innerTable {
  table-layout: fixed;
}

.tddiv {
  text-align: center;
  width: 200px;
  height: 200px;
}

You can use these settings: 您可以使用以下设置:

.innerTable {
  table-layout: fixed;
  background: #ddd;
  position: relative;
  left: 50%;
  transform: translateX(-50%);
  z-index: -1;
}

( z-index and background don't have to be, I just added them to make the visible result more obvious) z-indexbackground不是必须的,我只是添加了它们以使可见结果更加明显)

https://jsfiddle.net/afeetdjb/1/ https://jsfiddle.net/afeetdjb/1/

Try using flex like this 尝试像这样使用flex

 .outerTable { table-layout: fixed; display:flex; justify-content:center; overflow:hidden; /* overflow: hidden; */ } .innerTable { table-layout: fixed; } .tddiv { text-align: center; width: 200px; height: 200px; display: flex; justify-content:center; } 
 <table class="outerTable" align="center" border=1> <tr> <td valign=top> <div class="tddiv"> <table class="innerTable" width=300px height=300px border=1 align=center> </table> </div> </td> </tr> </table> 

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

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