首页 > 解决方案 > HTML表格;如何格式化第二列中的内容以对齐所有 - 除了第一个元素 - 向右并拉伸第一个元素以填充剩余宽度

问题描述

想要显示以下内容:

在此处输入图像描述

我已经尝试了以下方法,但它没有正确执行 - 而且它只适用于一定的宽度 - 如果我增加或减少宽度,事情就会变得丑陋:

减小宽度:

在此处输入图像描述

我当前的 HTML 如下所示:

<div id = "ProjectSelector" width = 100%>
        <table width = "100%" style = "padding-bottom: 10px;">
          <tr>
            <td style="white-space: nowrap; width: 140px;">Web Project (.csproj)</td>
            <td style="width: 99%;" ><input id = "webproj" style="width: 97%"/><button id="webproj_browse">...</button></td>
          </tr>
          <tr>
            <td>Root Namespace</td>
            <td style="width: 99%;"><input id = "rootnamespace" style="width: 99%"/></td>
          </tr>
          <tr>
            <td>Connection String</td>
            <td style="width: 99%;"><select id = "connectionstring" style = "width: 87%"></select><button id="newConnection">New Connection</button><button id="connstringDelete">Delete</button></td>
          </tr>
        </table>
      </div>

问题:如何格式化表格和第二列的内容以正确完成此操作?

标签: htmlcssformattingelement

解决方案


您问题的标题描述了典型的弹性行为。您可以在表格内使用 flex 容器:

.flex {
  display: flex;
}

.flex-1 {
  flex-grow: 1;
}
<div id="ProjectSelector" width=1 00%>
  <table width="100%" style="padding-bottom: 10px;">
    <tr>
      <td style="white-space: nowrap; width:0;">Web Project (.csproj)</td>
      <td>
        <div class="flex"><input id="webproj" class="flex-1" /><button id="webproj_browse">...</button></div>
      </td>
    </tr>
    <tr>
      <td>Root Namespace</td>
      <td>
        <div class="flex"><input id="rootnamespace" class="flex-1" /></div>
      </td>
    </tr>
    <tr>
      <td>Connection String</td>
      <td>
        <div class="flex">
          <select id="connectionstring" class="flex-1"></select><button id="newConnection">New Connection</button><button id="connstringDelete">Delete</button></div>
      </td>
    </tr>
  </table>
</div>

它也可以用 grid 或 flex 构建而不用 table。

对于 infos & demo,一个混合网格和 flex 的示例,我可能不会首先使用这个 HTML 结构 H + P

* {
  margin: 0;
}

.flex {
  display: flex;
}

.flex-1 {
  flex-grow: 1;
}

#ProjectSelector {
  display: grid;
  grid-template-columns: auto 1fr;
  grid-gap: 0.25em;
  ;
}

p {
  grid-column: 2;
}
<div id="ProjectSelector">
  <h4>Web Project (.csproj)</h4>
  <!-- title that matches your structure or else can be plain text -->
  <p class="flex"><input id="webproj" class="flex-1" /><button id="webproj_browse">...</button></p>
  <h4>Root Namespace</h4>
  <p class="flex"><input id="rootnamespace" class="flex-1" /></p>
  <h4>Connection String</h4>
  <p class="flex">
    <select id="connectionstring" class="flex-1"></select><button id="newConnection">New Connection</button><button id="connstringDelete">Delete</button></p>
</div>


推荐阅读