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

前端 未结 3 1598
[愿得一人]
[愿得一人] 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条回答
  • 2021-02-04 08:02

    This is easy to do with CSS if you have a fixed-size div:

    .keepcentered {
        position:    absolute;
        left:        50%;        /* Start with top left in the center */
        top:         50%;
        width:       200px;      /* The fixed width... */
        height:      100px;      /* ...and height */
        margin-left: -100px;     /* Shift over half the width */
        margin-top:  -50px;      /* Shift up half the height */
        border: 1px solid black; /* Just for demo */
    }
    

    The problem, of course, is that fixed-size elements aren't ideal.

    0 讨论(0)
  • 2021-02-04 08:15

    Try this little article about Horizontal and Vertical centering. It is a little old and has a few hacks but you should be able to work out some test code from it.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题