Reputation: 776
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>
Upvotes: 2
Views: 4673
Reputation: 2495
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>
Upvotes: 0
Reputation: 1427
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');}
}
Upvotes: 1