2

I'm struggling to center a fixed div inside another fixed div. I have tried many things but could not center it. How can i do this?

.overlay {
    background: rgba(0, 0, 0, .60);
    position: fixed;
    width: 100%;
    height: 100%;
    opacity: 1;
    -webkit-transition: opacity .25s ease;
    z-index: 3;
    margin: 0 auto;


}

.ques_preview_div {

    width: 60em;
    height: 30em;
    top: 20%;
    position: fixed;
    background-color: #adadad;
    margin: 0 auto;
    z-index: 4;
}
<div class="overlay">

<div class="ques_preview_div">

</div>

</div>

I could achieve what i needed by giving the position relative to ques_preview_div . But i need it to have position fixed.

Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
CraZyDroiD
  • 6,622
  • 30
  • 95
  • 182
  • look at this one http://stackoverflow.com/questions/2691178/how-to-make-a-div-center-align-in-html – xird Mar 08 '17 at 10:13
  • May I ask why you need .ques_prev_div to be fixed position it makes more sense to me to position it absolute in the fixed parent div – Steve K Mar 08 '17 at 10:18

3 Answers3

1

set right:0; left:0 to .ques_preview_div , check with the snippet full screen

.body {
    margin:0;
}
.overlay {
    background: rgba(0, 0, 0, .60);
    position: fixed;
    width: 100%;
    height: 100%;
    opacity: 1;
    -webkit-transition: opacity .25s ease;
    z-index: 3;
    margin: 0 auto;


}

.ques_preview_div {

    width: 60em;
    height: 30em;
    top: 20%;
    position: fixed;
    background-color: #adadad;
    margin: 0 auto;
    z-index: 4;
    right:0;
    left:0;
}
<div class="overlay">

<div class="ques_preview_div">

</div>

</div>
Jishnu V S
  • 8,164
  • 7
  • 27
  • 57
0

You can use the CSS3 property transform: translate(-50%, -50%); along with top and left.

.overlay {
  background: rgba(0, 0, 0, .60);
  position: fixed;
  width: 100%;
  height: 100%;
  opacity: 1;
  -webkit-transition: opacity .25s ease;
  z-index: 3;
  margin: 0 auto;
}

.ques_preview_div {
  width: 60em;
  height: 30em;
  position: fixed;
  background-color: #adadad;
  margin: 0;
  z-index: 4;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div class="overlay">
  <div class="ques_preview_div">
  </div>
</div>
Pugazh
  • 9,453
  • 5
  • 33
  • 54
0

Use pixels (px) instead of em on your width and hight of class ques_preview_div

.overlay {
    background: rgba(0, 0, 0, .60);
    position: fixed;
    width: 100%;
    height: 100%;
    opacity: 1;
    -webkit-transition: opacity .25s ease;
    z-index: 3;
    margin: 0 auto;


}

.ques_preview_div {

    width: 60px;
    height: 30px;
    top: 20%;
    position: fixed;
    background-color: #adadad;
    margin: 0 auto;
    z-index: 4;
}
<div class="overlay">

<div class="ques_preview_div">

</div>

</div>
Serge Inácio
  • 1,366
  • 9
  • 22