Friday 9 March 2012

CSS: input text inside table cell without overflow

   


If you ever worked with forms and tables together (and I believe you have at least once in your web developing career), you surely have found that input boxes width can be difficult to manage.
Presume you have a table and inside a <td> you have an input text box which should have a 100% width. The input box should stay inside the <td> and fill all the available space. However that doesn't happen, and the input box overflows the available space. Why?

Explanation
The reason is because you have set borders and paddings. Let me show you an example: your input box has a width set to 100%, a border of 1px each side and a padding of 2px each side. That means, the input box width will be:
100% + 2*(2px+1px) = 100% + 6px
Those extra 6 pixels are your trouble, and the input box will overflow by those 6px.


Solution
Someone can suggest to simply reduce the width to 95% or something like that. Well, that solution could surely work. However, there's a more interesting and efficient way of dealing with the issue.
The input box should be wrapped inside a container (a div for example). We can style the container the way we prefer (borders, radius, shadows etc.). Then we style the input box as the container's child.
<div class="wrapper"><input name="textfield" type="text" value=""></div>

CSS
The rules here presented are just an example, but they give us a full range of possible styling.
.wrapper {
    background-color: #FFFFFF;
    padding: 2px 2px 2px 20px;
    -moz-border-radius: 4px;
    -webkit-border-radius: 4px;
    border-radius: 4px;
    -webkit-box-shadow: 0 0 4px #000000;
    -moz-box-shadow: 0 0 4px #000000;
    box-shadow: 0 0 4px #000000;
    border-top: 1px solid #FFFFFF;
    border-right: 1px solid #FFFFFF;
    border-bottom: 1px solid #FFFFFF;
    border-left: 1px solid #FFFFFF;
    behavior:   url(/PIE/PIE.htc);
}
.wrapper input {
    background-color: #FFFFFF;
    color: #000000;
    font-family: Tahoma;
    font-size: 14px;
    font-weight: bold;
    border: none #FFFFFF;
}
When we display the input box, it will just stay inside the td width, without any overflow.

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.