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

前端 未结 3 1599
[愿得一人]
[愿得一人] 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.

提交回复
热议问题