代码之家  ›  专栏  ›  技术社区  ›  showkey

为什么不能将子级宽度和高度设置为与父级相同?

  •  0
  • showkey  · 技术社区  · 7 年前

    父元素是DIV,宽度为300px,高度为40px,输入子元素。

    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%;' 会使孩子比父母大。

    2 回复  |  直到 7 年前
        1
  •  1
  •   Vadim Hulevich    7 年前

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

    myinput.style.cssText ='width:100%;height:100%;box-sizing: border-box;'
    
        2
  •  1
  •   Niraj Kaushal    7 年前

    默认情况下 input border-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>