开发者

How to have a text input with padding fill its container

开发者 https://www.devze.com 2023-01-06 17:09 出处:网络
Of course, width: 100% on a block element fills the container, but only if border, padding, and margin are zero. Putting such an input in a containing div with padding does the trick开发者_运维百科, b

Of course, width: 100% on a block element fills the container, but only if border, padding, and margin are zero. Putting such an input in a containing div with padding does the trick开发者_运维百科, but I'm curious why simply input {display: block; width: auto;} doesn't work. Suggestions?


I agree with centr0 as to why width: auto doesn't work.

If you actually want to get an input to be full width of its container, then the following works. Given:

<div id="Container">
    <form>
        <input type="text" />
    </form>
</div>

Do this with the css:

form {
    padding: 0 0 0 14px; 
    }

input {
    padding: 5px;
    width: 100%;
    margin: 0 0 0 -14px;
}

Explanation: Obviously, the -14px margin on the input counteracts the padding added to the form element. What is not so obvious is where the 14px came from. It is equal to the left/right 5px padding of the input plus the default for input element's border width (2px on all the browsers I tested). So 2 + 5 + 5 + 2 = 14.

To really be sure you are consistent cross-browser, you would want to explicitly set the border width to what you desired for the input. If you want a different padding (or thicker/thinner borders), then just redo the math. A 3px padding would be 10px instead of 14px, a 7px padding would be 18px instead of 14px.

For the example, you can set the width of #Container (could also be the body itself that is just defaulting to 100% of the page width) to what you desire, and the above css should match its width.


if i remember correctly the default size of input doesn't span the width of its container. "width: auto;" is like "resetting" the style back to its default value.


If you aren't using a Reset CSS Stylesheet then the input element will have some default styling set by the browser, this probably includes padding and margins.

also, width:auto will give the browser default. Try width:100%


Reset the container's padding resolves the problem.

td {
  padding: 0 1em;
}
0

精彩评论

暂无评论...
验证码 换一张
取 消