【问题标题】:How can i position the table head on the left of table body with css only如何仅使用 css 将表头定位在表体左侧
【发布时间】:2023-02-03 19:50:51
【问题描述】:

enter image description here 您好,th's 和 td's 似乎排成一排,我怎样才能得到这种效果?这是 HTML

`<table>
            <thead>
                <tr>
                    <th>First Name</th>
                    <th>Last Name</th>
                    <th>Job Title</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td>James</td>
                    <td>Matman</td>
                    <td>Chief Sandwich Eater</td>
                </tr>
                <tr>
                    <td>Jon</td>
                    <td>Doe</td>
                    <td>Chief Executive Eater</td>
                </tr>
            </tbody>
        </table>

@media (max-width:360px){
    thead {
        float: left
    }
    th{
        display: block;
    }
    tbody {
        float: right
    }
    td{
        margin: 0px;
        display: block;
    }
}`

这是我目前的尝试,但离我需要的结果还很远

【问题讨论】:

  • 试试tr {display: inline-flex;flex-direction: column;}其他类似的SO问题:123
  • 但是因为你需要重复标题我认为你需要javascript ..从来没有走那么远
  • 你关心头部包裹在标签内吗?
  • 使用具有两列且没有标题的表格,并使用第一列作为标签(例如,名字、姓氏……)。

标签: css tr


【解决方案1】:

你想要的只能通过重复 tr 和 th 来完成,这会使代码越来越长。这是你的例子。

如果你不想四周都是边框,你可以使用:border-bottom,border-top。

tr {
  display: inline-flex;
  flex-direction: column;
  }
  td , th{
    padding: 5px;
     border: 1px solid black; 
  }
  
<table>
  <tr>
    <th>Header 1</th>
    <th>Header 2</th>
    <th>Header 3</th>
  </tr>
  <tr>
    <td>Row 2, Column 1</td>
    <td>Row 2, Column 2</td>
    <td>Row 2, Column 3</td>
  </tr>
</table>

你应该看看它是如何使用SmartyTwig模板完成的。
聪明人:

    <table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    {foreach from=$data item=row}
      <tr>
        <td>{$row.col1}</td>
        <td>{$row.col2}</td>
      </tr>
    {/foreach}
  </tbody>
</table>

Twig:使用 for 或 foreach。

    <table>
  <thead>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
  </thead>
  <tbody>
    {% for row in data %}
      <tr>
        <td>{{ row.col1 }}</td>
        <td>{{ row.col2 }}</td>
      </tr>
    {% endfor %}
  </tbody>
</table>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-11-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-12
    • 1970-01-01
    • 1970-01-01
    • 2017-09-23
    相关资源
    最近更新 更多