Alter
Alter

Reputation: 3464

Tables cells - make children take full width but not overflow

I'm trying to add child elements to a table cell, I want the children to be as wide as they can without overflowing. My problem is that they do not automatically take up the full width, and if I set the width to 100%, they will overflow.

I don't want to simply hide the overflow, because I'd like to put borders around the children in the future.
Javascript is an unfavoured solution for unmentioned reasons; but if it works, it works.

This is my test:

<table style="background:grey;width:500px">
    <tr>
        <td>
            <input value="Hello World"></input>
        </td>
    </tr>
    <tr>
        <td>
            <input style="width:100%" value="Hello World"></input>            
        </td>
    </tr>
</table>

I've tried a few things that other people have posted (such as making the input's display an inline-block, making the cell width 100%, border-collapse the table). I'm using the latest firefox browser.

Upvotes: 1

Views: 173

Answers (2)

Adam Fratino
Adam Fratino

Reputation: 1241

Add box-sizing: border-box; to the input element CSS.

DEMO: http://jsfiddle.net/kb9x06cg/

Here's a great article from Paul Irish about box-sizing: http://www.paulirish.com/2012/box-sizing-border-box-ftw/

And here's MDN's write-up on the subject: https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing

Upvotes: 2

Marc Audet
Marc Audet

Reputation: 46795

input fields have extra width due to padding and borders. If you apply box-sizing: border-box you will get the computed width to be 100% instead of 100%+padding+border.

table {
  background-color: gray;
  width: 500px;
}
table input {
  box-sizing: border-box;
  width: 100%;
}
<table>
    <tr>
        <td>
            <input value="Hello World"></input>
        </td>
    </tr>
    <tr>
        <td>
            <input value="Hello World"></input>            
        </td>
    </tr>
</table>

Upvotes: 1

Related Questions