How to position overlay fixed div to the center with css?

前端 未结 3 1736
闹比i
闹比i 2021-01-04 13:31

I have a div that appears once I have clicked some action to another element in the website. It is a fixed div that appears on top of all divs and

相关标签:
3条回答
  • 2021-01-04 13:59

    I just Practiced before pasting here

    .overlay-box {
        position:absolute;
        top:50%;
        left:50%;
        transform:translate(-50%, -50%);
        color: white; background: #666666; opacity: .8;
        z-index: 1000;
    }
    
    0 讨论(0)
  • 2021-01-04 14:13

    Put the div inside another div which is 100% width and text-align center. Also set .overlay-box {margin: auto}

    .container-box {
       background-color:#000;
       width:100%;
       height: 100%;
       text-align:center;
    }
    .overlay-box {
       background-color:#fff;
       width:300px;
       margin: auto;
    }
    
    
    <div class="container-box">
      <div class="overlay-box">Some content</div>
    </div>
    

    Working JSFiddle: https://jsfiddle.net/5kkdaqe6/

    0 讨论(0)
  • 2021-01-04 14:15

    You can set top, right, bottom, left to 0 and margin to auto to vertically and horizontally center align fixed div. But this will only work if you set the height of div using CSS.

    .overlay-box {
        background-color: #fff;
        border: 1px solid #000;
        text-align:center;
        height: 200px;/*height needs to be set*/
        width: 550px;
        margin: auto;
        position: fixed;
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
    }
    

    If you can't set the height then consider using flex layout https://css-tricks.com/snippets/css/a-guide-to-flexbox/

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