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

前端 未结 14 1677
庸人自扰
庸人自扰 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: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:

    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 */ 
    }
    

提交回复
热议问题