Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS: center textarea inside <td> for 100% table

Tags:

html

css

Currently

I have a 100% width table that contains 2 columns within which there is a textarea where users can input text.

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>

enter image description here

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

Problem

I want the text area to dynamically adjust to the screen width, and keep margins to the surrounding cell constant e.g. 10px <-- as per this example.

Goal:

enter image description here

I would like to keep the structure of the table and divs the same if this is possible to achieve the desired result.

like image 802
Wronski Avatar asked Oct 14 '25 03:10

Wronski


2 Answers

Simply use display:flex for your container and then use the margin for textarea. I hope this solution will be helpful for you.

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>
like image 153
Saravana Avatar answered Oct 18 '25 02:10

Saravana


You don't need anything complicated here. You've simply run into the classic box model issue, where the total width includes the left and right padding and borders as well as the specified width. The box-sizing property can be used to switch to the alternate box model where the width property is the total width.

textarea {
    box-sizing: border-box;
}
like image 28
Kravimir Avatar answered Oct 18 '25 02:10

Kravimir