8

I often find that if I create or reparent DOM nodes in javascript, the CSS engine doesn't recalculate the sizes of the parent containers. This happens in Firefox and Chrome.

For example, the body might stay the same size while new content overflows the bottom. If I resize the window the body grows, but it doesn't "lock in" to its correct size until the window is sized to be at least as big as the body should be.

Is there a way to trigger a full layout recomputation in Javascript?

4
  • 3
    Sounds like you're doing something wrong in your styling, as this shouldn't really be an issue ? Commented Jan 10, 2014 at 22:45
  • Do you have these set? html { height: 100%; } body { min-height: 100%; } Commented Jan 10, 2014 at 22:47
  • I'm using this method. Commented Jan 10, 2014 at 22:48
  • 3
    Can you give us a simple HTML example? Commented Jan 10, 2014 at 22:50

4 Answers 4

2

I can able to trigger CSS Engine via:

document.body.style.zoom = 1.0000001;
setTimeout(function(){document.body.style.zoom = 1;},50); //allow some time to flush the css buffer.

For every time after resizing the window use the following:

$(window).resize(function() {
    if(this.resizeTO) clearTimeout(this.resizeTO);
    this.resizeTO = setTimeout(function() {
        $(this).trigger('resizeEnd');
    }, 500);
});
$(window).bind('resizeEnd', function() {
    document.body.style.zoom = 1.0000001;
    setTimeout(function(){document.body.style.zoom = 1;},50);
});
Sign up to request clarification or add additional context in comments.

1 Comment

Zoom changes may trigger a redraw, but not a box recomputing. Seems at least firefox' current parsing engine will only recompute a layout component if there's an actual size change on that specific element...
1

You can trigger a repaint from JavaScript by setting a CSS style to an innocuous value, e.g.

document.body.style.zIndex = 1;

Comments

0

Yes. I tend to put a random className on the <html> element, using:

document.documentElement.className = 'reflow_' + (new Date()).getTime();

which creates:

<html class="reflow_1483757400611">

Tried and tested on everything from Android Browser 4 to Smart TV's via camposat.tv

Comments

0

The browser does recompute the geometry of all elements after DOM manipulation. One likely reason you might see an element "stuck" at a certain height even after its content has changed is this CSS rule:

body { height: 100% };

It tells the browser, make the body element as large in height as the viewport regardless of its content.

Try changing it to:

body { min-height: 100% };

This will tell the browser to make body at least as large in height as the viewport or larger if there is more content.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.