1

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>
thekthuser
  • 706
  • 1
  • 12
  • 28
  • 1
    Divs are always going to be on top of each other. They're block elements. You would have to change the display to like inline or inline block to get that effect. – nickn Jun 24 '16 at 20:01

2 Answers2

1

not sure, but have you tried it?

    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');}
    }
danielarend
  • 1,379
  • 13
  • 26
0

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>
CascadiaJS
  • 2,320
  • 2
  • 26
  • 46