18

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 the background is darkened. I need to make sure that this div has been positioned to the center, and stays in the center even if the window is re-sized.

I have tried the left, margin-left:50% trick, but it's not doing the job.

Here's my code:

<div class="overlay-box">Some content</div>

CSS

.overlay-box {
background-color:#fff;
        width:550px;
left:50%;
    margin-left:-275px;
position:fixed;
text-align:center;
border:1px solid #000;
}

It doesn't position at center, and upon resizing it has a bigger margin towards the left than the right. How do I fix this? Is there a magic trick like margin:0px auto for fixed divs?

  • Possible duplicate of [Horizontally center a div in another div with width: 100%](http://stackoverflow.com/questions/114543/horizontally-center-a-div-in-another-div-with-width-100) – Hidden Hobbes Mar 14 '16 at 14:36
  • 1
    Hidden Hobbes, does **"How to position overlay fixed div to the center with css?"** look same as **"Horizontally center a div in another div with width: 100%"**? –  Mar 14 '16 at 14:38
  • There are techniques in the linked question that are viable in this instance (e.g. http://stackoverflow.com/a/29011864/3400962). Personally I can't see what is wrong with the code you provided https://jsfiddle.net/zfd0Ltxn/1/. – Hidden Hobbes Mar 14 '16 at 14:57

3 Answers3

38

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;
}
Dev Matee
  • 5,525
  • 2
  • 27
  • 33
2

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/

Mario
  • 420
  • 1
  • 11
  • 23
2

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/

Naman Nehra
  • 630
  • 4
  • 10
  • 4
    I still find it laughable that there is so much faffing about with CSS to do basic, simple things. – Epirocks May 23 '17 at 12:45