Search code examples
javascriptcsshtmlpositioning

Is it OK to use JavaScript to reposition elements when window is resized?


I am trying to accomplish a positioning scheme that is hard with CSS alone. I could do it easily with JavaScript, using something like:

function onWindowResize(new_width,new_height){
    $('#element')
       .css({  left: some_function(new_width),
               top: another_function(new_height) });
};

Is it OK to use that approach? What would be possible drawbacks?


Solution

  • Sure, it's perfectly fine to do it with javascript if you want. Some resize operations require more complicated logic than can be expressed in pure CSS.

    In many cases, it can be done with pure CSS too. If you show us what you were really trying to accomplish, you might get some CSS-only suggestions.

    Potential drawbacks:

    1. Your page requires javascript in order to function properly (not much of an issue these days in my opinion).
    2. The layout may not track quite as smoothly during resizing of the window compared to a CSS only solution.