How to keep a floating div centered on window resize (jQuery/CSS)

前端 未结 3 1600
[愿得一人]
[愿得一人] 2021-02-04 07:42

Is there a way (without binding to the window.resize event) to force a floating DIV to re-center itself when the browser window is resized?

To help explain, I imagine th

3条回答
  •  梦毁少年i
    2021-02-04 08:16

    The simplest way would be with the following CSS code:

    #floating-div {
        width: 50%;
        border: 1px solid gray;
        margin: 0 auto;
    }
    

    The key line of CSS code above is the "margin: 0 auto;" which tells the browser to automatically set the left/right margins to keep the div centered on the page, even when you resize the browser window.

提交回复
热议问题