thekthuser thekthuser - 5 months ago 11
CSS Question

Detect if child divs are wider than parent?

How can I detect if multiple child divs are wider than their parent? In this case, when they are wider, the rightmost one is displayed below the leftmost one. I have tried using js to check for an overflow (as described here: javascript css check if overflow), but it doesn't work.

Ultimately, I want to keep the rightmost div below its sibling and change its padding, but only when they are wider.

The code is basically this:

<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>

Answer

This will compare the child width and the parent width of your divs

$('.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>

Comments