【问题标题】:compute outerHeight with margins at parent用父级边距计算 outerHeight
【发布时间】:2016-01-10 01:12:42
【问题描述】:

给定

<div id="parent>
  <div id="child" style="height:10px;margin:5px;padding:2px"></div>
</div>

我想计算父级的高度(包括边距)。我找不到合适的方法。

console.log($('#parent').outerHeight());        //= 14
console.log($('#parent').outerHeight(true));    //= 14
console.log($('#parent')[0].offsetHeight);      //= 14
console.log($('#parent')[0].getBoundingClientRect().height); //=14

//but
console.log($('#child').outerHeight());         //= 14
console.log($('#child').outerHeight(true));     //= 24 !!

这是它的 jsfiddle:https://jsfiddle.net/estani/w0ro2Lsw/3/

【问题讨论】:

标签: javascript jquery html css height


【解决方案1】:

子元素的边距在父元素之外。但它们不是父元素的边距,这就是为什么 outerHeight 没有注意到它们的原因。

查找父级高度+子级边距的最佳方法取决于您的用例:

  • 如果子元素是父元素中的唯一元素,并且您想使用边距使父元素大于子元素,我建议将padding:5px 给父元素而不是margin:5px孩子。

  • 添加overflow:auto 将使父级包含子级的边距。

  • 如果您希望孩子和父母共享边距,请将margin:5px 给父母。

在所有这些情况下,outerHeight 都会返回您想要的值。

【讨论】:

    【解决方案2】:

    您的子 div 溢出了父 div。你可以在你的父 div 中使用它:

    overflow:auto
    

    示例代码:

    <div id="parent" style='overflow:auto'>
    

    【讨论】:

      【解决方案3】:

      设置父“display:inline-block;

      This is the JSFiddle

      【讨论】:

        猜你喜欢
        • 2013-10-14
        • 1970-01-01
        • 2021-06-14
        • 2014-06-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-15
        • 1970-01-01
        相关资源
        最近更新 更多