width: 100%-padding?

2018-12-31 15:22发布

I have an html input.

The input has padding: 5px 10px; I want it to be 100% of the parent div's width(which is fluid).

However using width: 100%; causes the input to be 100% + 20px how can I get around this?

Example

14条回答
何处买醉
2楼-- · 2018-12-31 15:48

box-sizing: border-box is a quick, easy way to fix it:

This will work in all modern browsers, and IE8+.

Here's a demo: http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

The browser prefixed versions (-webkit-box-sizing, etc.) are not needed in modern browsers.

查看更多
荒废的爱情
3楼-- · 2018-12-31 15:56

What about wrapping it in a container. Container shoud have style like:

{
    width:100%;
    border: 10px solid transparent;
}
查看更多
情到深处是孤独
4楼-- · 2018-12-31 15:58

I had the same issue. Fix it like so:

width: 100%;
padding: 5px;
/*--------------Now remove from padding what you've added---------------*/
margin:-5px;

Cheers

查看更多
明月照影归
5楼-- · 2018-12-31 16:01

You can try some positioning tricks. You can put the input in a div with position: relative and a fixed height, then on the input have position: absolute; left: 0; right: 0;, and any padding you like.

Live example

查看更多
若你有天会懂
6楼-- · 2018-12-31 16:01

Move the input box' padding to a wrapper element.

<style>
div.outer{ background: red; padding: 10px; }
div.inner { border: 1px solid #888; padding: 5px 10px; background: white; }
input { width: 100%; border: none }
</style>

<div class="outer">
    <div class="inner">
       <input/>
    </div>
</div>

See example here: http://jsfiddle.net/L7wYD/1/

查看更多
怪性笑人.
7楼-- · 2018-12-31 16:02

Try this:

width: 100%;
box-sizing: border-box;
查看更多
登录 后发表回答