首页 > 解决方案 > CSS:100%表格的中心文本区域

问题描述

目前

我有一个 100% 宽度的表格,其中包含 2 列,其中有一个文本区域,用户可以在其中输入文本。

table {
  border-collapse: collapse;
  width: 100%;
  border: 1px solid black;
  table-layout: fixed;
}

th,
td {
  text-align: center;
  border: 1px solid black;
  padding: 10px;
}

.container {}

.text-area {
  width: 100%;
}
<table>
  <tbody>
    <tr>
      <th>Column 1</th>
      <th>Column 2</th>
    </tr>
    <tr>
      <td>
        <div class="container">
          <textarea class="text-area">This is a short piece of text.
            </textarea>
        </div>
      </td>
      <td>
        <div class="container">
          <textarea class="text-area">This is a long piece of text, which ultimately should be displayed as a minimum with a width of 250 px
            </textarea>
        </div>
      </td>
    </tr>
  </tbody>
</table>

在此处输入图像描述

https://jsfiddle.net/qvr2b8pu/3/

问题

我希望文本区域动态调整到屏幕宽度,并保持周围单元格的边距不变,例如 10px <-- 按照这个例子。

目标:

在此处输入图像描述

如果可以达到预期的结果,我想保持表格和 div 的结构相同。

标签: htmlcss

解决方案


只需使用display:flexfor your container,然后使用 margin for textarea。我希望这个解决方案对您有所帮助。

table {
    border-collapse: collapse;
    width: 100%;
    border: 1px solid black;
    table-layout: fixed;
}

th,
td {
    text-align: center;
    border: 1px solid black;
    padding: 5px;
}

.container {
    display: flex;
}

.text-area {
    width: 100%;
    margin: 5px;
}
<table>
    <tbody>
        <tr>
            <th>Column 1</th>
            <th>Column 2</th>
        </tr>
        <tr>
            <td>
                <div class="container">
                    <textarea class="text-area">This is a short piece of text.
                    </textarea>
                </div>
            </td>
            <td>
                <div class="container">
                    <textarea class="text-area">This is a long piece of text, which ultimately should be displayed as a minimum with a width of 250 px
                    </textarea>
                </div>
            </td>
        </tr>
    </tbody>
</table>


推荐阅读