How to make an element width: 100% minus padding?

前端 未结 14 1458
庸人自扰
庸人自扰 2020-11-21 07:33

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 widt

相关标签:
14条回答
  • 2020-11-21 08:15

    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.

    0 讨论(0)
  • 2020-11-21 08:15

    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>).

    0 讨论(0)
  • 2020-11-21 08:15

    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/

    0 讨论(0)
  • 2020-11-21 08:15

    Try this:

    width: 100%;
    box-sizing: border-box;
    
    0 讨论(0)
  • 2020-11-21 08:17

    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 */ 
    }
    
    0 讨论(0)
  • 2020-11-21 08:17

    Assuming i'm in a container with 15px padding, this is what i always use for the inner part:

    width:auto;
    right:15px;
    left:15px;
    

    That will stretch the inner part to whatever width it should be less the 15px either side.

    0 讨论(0)
提交回复
热议问题