leviathanbadger
leviathanbadger

Reputation: 1712

Detecting when a div overflows

I'm trying to make my website flow depending on the size of the screen. I created this: http://jsfiddle.net/aboveyou00/7NeZz/1/. It is working well enough. The two inside divs are centered and next to each other on the same line, when they fit - but when they don't, they're centered each on their own line.

Here's the HTML. The CSS and JavaScript are in the fiddle.

<div class="divContainer">
  <div class="div1">
    <img src="http://placehold.it/200x300/EEEEEE/000000" />
  </div>
  <div class="div2"></div>
</div>

The problem is, now I'm trying to figure out how to make the formatting for div2 change depending on whether or not it was pushed to the next line. If it is on the same line, then the inside text should be aligned to the left. If it was moved to the bottom, then the inside text should be center-aligned.

Constraints: I can use javascript, and jQuery, if needed. A CSS-only solution is preferred, but not expected.

How do I do this?

Upvotes: 2

Views: 71

Answers (1)

Explosion Pills
Explosion Pills

Reputation: 191809

Not completely sure that I understand your question, but if there is no content surrounding the above and the widths are fixed, you can use a fairly trivial media query to change the style of the second div when the container gets too small.

@media all and (max-width: 520px) {
    div.div2 {
        text-align: center;
    }
}

http://jsfiddle.net/ExplosionPIlls/7NeZz/2/

If you don't know the widths or if there is more complicated stuff going on, you can compare the combined widths of the two divs to the container on resizing.

$(window).on('resize', function () {
    if ($(".div1").width() + $(".div2").width() > $(".divContainer").width()) {
        $(".div2").css('text-align', 'center');
    }
    else {
        $(".div2").css('text-align', 'left');
    }
});

$(window).trigger('resize');

http://jsfiddle.net/ExplosionPIlls/7NeZz/3/

Upvotes: 2

Related Questions