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 16:07

Use padding in percentages too and remove from the width:

padding: 5%;
width: 90%;
查看更多
荒废的爱情
3楼-- · 2018-12-31 16:08

Just understand the difference between width:auto; and width:100%; Width:auto; will (AUTO)MATICALLY calculate the width in order to fit the exact given with of the wrapping div including the padding. Width 100% expands the width and adds the padding.

查看更多
柔情千种
4楼-- · 2018-12-31 16:09

You can do it without using box-sizing and not clear solutions like width~=99%.

Demo on jsFiddle:
enter image description here

  • Keep input's padding and border
  • Add to input negative horizontal margin = border-width + horizontal padding
  • Add to input's wrapper horizontal padding equal to margin from previous step

HTML markup:

<div class="input_wrap">
    <input type="text" />
</div>

CSS:

div {
    padding: 6px 10px; /* equal to negative input's margin for mimic normal `div` box-sizing */
}

input {
    width: 100%; /* force to expand to container's width */ 
    padding: 5px 10px;
    border: none;
    margin: 0 -10px; /* negative margin = border-width + horizontal padding */ 
}
查看更多
路过你的时光
5楼-- · 2018-12-31 16:11

This is why we have box-sizing in CSS.

I’ve edited your example, and now it works in Safari, Chrome, Firefox, and Opera. Check it out: http://jsfiddle.net/mathias/Bupr3/ All I added was this:

input {
  -webkit-box-sizing: border-box;
     -moz-box-sizing: border-box;
          box-sizing: border-box;
}

Unfortunately older browsers such as IE7 do not support this. If you’re looking for a solution that works in old IEs, check out the other answers.

查看更多
人气声优
6楼-- · 2018-12-31 16:12

Here is the recommendation from codeontrack.com, which has good solution examples:

Instead of setting the width of the div to 100%, set it to auto, and be sure, that the <div> is set to display: block (default for <div>).

查看更多
人间绝色
7楼-- · 2018-12-31 16:12

You can do this:

width: auto;
padding: 20px;
查看更多
登录 后发表回答