html - 如何将单元格内容填充到中心 <td>

标签 html css

例如,如果我有一个固定长度的文本,那么我可以很容易地将它居中

enter image description here

但是,假设有可变长度的数据,

enter image description here

将昵称内容居中会影响可读性。有没有办法根据最长的长度填充内容并将其居中?

<td>
    <div style="padding-left: 30%;">
       ...content
    </div>
</td>

值“30%”只是对昵称的粗略估计。

enter image description here

但是,如果该列需要更长的数据,这 30% 将会改变。以编程方式确定我设置为“30”的这个值的好方法是什么?

更新,居中文本不是我要找的。我想居中文本并左对齐,单独居中文本会给我

enter image description here

我想要的视觉表现

enter image description here

最佳答案

您需要javascript来确定内容的宽度和表格数据的宽度。

 var td = document.querySelectorAll('td > div');
    var width = 0;
    var clientWidth = 0;
    // determine the width
    [].forEach.call(td, function(e) {
      clientWidth = e.parentNode.clientWidth; // the width is the same for all td's
      if (e.clientWidth > width) {
        width = e.clientWidth;
      }
    });
    // set the padding
    [].forEach.call(td, function(e) {
      e.style.paddingLeft = (clientWidth - width) / 2 + 'px';
      e.style.paddingRight = (clientWidth - width) / 2 + 'px';
    });    
    table {
      border-collapse: collapse;    
    }
    th {
      text-align: center;
    }
    th, td {
      border: 1px solid #000;
    }
    td > div {
      display: inline-block; /* set this because we want to calculate the width, block element has 100% */
      padding: 10px 0;
    }
  <table style="width: 50%">
    <tr>
      <th>Nickname</th>
    </tr>
    <tr>
      <td><div>Data 1 Data 1Data 1Data 1</div></td>
    </tr>
    <tr>
      <td><div>Data 2</div></td>
    </tr>
    <tr>
      <td><div>Data 3</div></td>
    </tr>
    <tr>
      <td><div>Data 4</div></td>
    </tr>
    <tr>
      <td><div>Data 5</div></td>
    </tr>
    <tr>
      <td><div>Data 6</div></td>
    </tr>
    <tr>
      <td><div>Data 7</div></td>
    </tr>
    <tr>
      <td><div>Data 8</div></td>
    </tr>
  </table>

更改硬编码的表格宽度以查看效果。

关于html - 如何将单元格内容填充到中心 <td>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38494628/

相关文章:

javascript - 来自数据库的实时新闻行情

html - Bootstrap Toggle Button,如何改变大小(高度和体重)

javascript - 为什么我网站的 slider 只能在 Mac(同一浏览器)上正常工作?

Css 仅条纹文本阴影效果

javascript - 使用预加载器延迟 css 动画?

javascript - 悬停不适用于图片库

html - CSS :before & position: relative issue in IE

html - 我的 CSS 下拉菜单中需要第三级

html - 在CSS中使用网格时,是否可以使网站滚动?

html - 应用渐变的图像 : better performance adding gradients via css or apply them directly to the src img?