Div height with child margin

2019-06-26 19:54发布

I have 2 divs and I want to make their height equal:

var highestCol = $('#SecondColumn').height();
$('.column').first().height(highestCol);

I know that second div is always higher than first one. When there is plain text in both divs everything works fine. But after adding divs with some margin or padding into second div (always higher) the calculatio breaks. It takes height of higher div but ignores sum of all margins of child divs inside second column.

How can I calculate full div with margins/paddings?

3条回答
forever°为你锁心
2楼-- · 2019-06-26 20:29

I think you want outerHeight(true) rather than 'height()' to include the margins/paddings.

The 'true' refers to including the margins or not.

查看更多
成全新的幸福
3楼-- · 2019-06-26 20:34

try this:

var highestCol = $('#SecondColumn')[0].offsetHeight;
$('.column').first().height(highestCol);
查看更多
别忘想泡老子
4楼-- · 2019-06-26 20:45

I think He meant what happens when the first and/or last child of an element have bottom/top margins values assigned. This is specially common with paragraph tags, since they have a margin bottom and top of 1em. This is consistent with the collapsing margins mentioned in the box model specification

http://www.w3.org/TR/CSS2/box.html#collapsing-margins

In this cases jQuery reports an outerHeight for the parent element that doesn't considers the top margin of the first child nor the bottom margin of the last child.

A solution for this is to set up a bottom/top margin for the parent and a bottom/top padding in order to keep consistency with the element's natural height:

.parent-element{
  padding-top: 1px;
  margin-top: -1px;
  padding-bottom: 1px;
  margin-bottom: -1px;
}

Here's a live sample, hopefully this might come in handy to someone:

http://jsfiddle.net/smqryr05/1

Cheers!!

查看更多
登录 后发表回答