【问题标题】:Why can't set child width and height as same as the parent?为什么不能将孩子的宽度和高度设置为与父母相同?
【发布时间】:2018-12-30 11:58:00
【问题描述】:

父元素为div,宽度为300px,高度为40px,子元素为input。

myinput = document.getElementById("e2");
myinput.style.cssText ='width:100%;height:100%;padding:0px;margin:0px;'
div{
    width:300px;
    height:40px;
    border:1px solid red;
}
<div id="e1"><input id="e2" type="text" /></div>

我想将孩子的宽度和高度设置为与父母相同,
myinput.style.cssText ='width:100%;height:100%;' 会使孩子大于父母。

【问题讨论】:

标签: javascript html css


【解决方案1】:

你需要添加box-sizing: border-box;

myinput.style.cssText ='width:100%;height:100%;box-sizing: border-box;'

【讨论】:

    【解决方案2】:

    默认情况下inputborder-width: 2px; 所以你必须设置输入的border-width:0px; 如下

    myinput = document.getElementById("e2");
    myinput.style.cssText ='width:100%;height:100%;padding:0px;margin:0px;border-width:0px;'
    div{
        width:300px;
        height:40px;
        border:1px solid red;
    }
    <div id="e1"><input id="e2" type="text" /></div>

    【讨论】: