检测 child div 是否比 parent 宽?

Detect if child divs are wider than parent?

如何检测多个 child div 是否比它们的 parent 宽?在这种情况下,当它们变宽时,最右边的显示在最左边的下方。我曾尝试使用 js 检查溢出(如此处所述:javascript css check if overflow),但它不起作用。

最终,我想将最右边的 div 保留在其同级下方并更改其填充,但前提是它们更宽。

代码基本上是这样的:

<div class='parent'>
  <span>title</span><br />
  <div class='child'>
    Some content.
  </div>
  <div class='child'>
    More content that sometimes doesn't fit.
  </div>
</div>

不确定,但是你试过了吗?

    var children = YourParentDiv.children;
    for (var i = 0; i < children.length; i++) {
       var child_width=children[i].offsetWidth;
       var parent_width = children[i].parentElement.offsetWidth;
       if (child_width>parent_width)
       {console.log('wider');}
    }

这将比较您的 div 的子宽度和父宽度

$('.parent').children('.child').each(function() {
  let $this = $(this);
  console.log($this.width(), '   ', $('.parent').width());
  if ($this.width() > $('.parent').width()) {
    //add the padding you want
    $this.css('padding-top', '10px');
  }
})
.parent {
  width: 500px;
}
.child {
  background-color: green;
  width: 700px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class='parent'>
  <span>title</span>
  <br />
  <div class='child'>
    Some content.
  </div>
  <div class='child'>
    More content that sometimes doesn't fit.
  </div>
</div>