0

I want to center a div with position fixed. And its width is specified as 300px and not in percentage.

<div class="mainCont">
  <div class="childCont">
</div>

childCont is div with fixed pos and width 300px. I want to make it as center.

Mr_Green
  • 40,727
  • 45
  • 159
  • 271

3 Answers3

1

Use following css:

.childCont {
    left: 50%;
    position: fixed;
    top: 50%;
    transform: translate(-50%, -50%);
    width: 300px;
}

Working Fiddle

ketan
  • 19,129
  • 42
  • 60
  • 98
  • How it is different from the already posted answer by WisdmLabs? – Mr_Green Mar 28 '16 at 04:57
  • @Mr_Green there is not required `translate3d` . Check my fiddle – ketan Mar 28 '16 at 04:58
  • I thought the same but later realized it must be preferred always for performance. check my comment on that post. – Mr_Green Mar 28 '16 at 04:59
  • @Mr_Green it is working inn IE11 also. Check my fiddle in IE11 – ketan Mar 28 '16 at 05:00
  • Sorry IE10. but it happens sometimes with mix of other css properties. But still your answer is similar to already posted one. You should upvote that instead. and I am not the downvoter. – Mr_Green Mar 28 '16 at 05:01
  • @Mr_Green I don't think that my answer answer is similar to that one. I used totally different property than that one. And working on all latest browser. – ketan Mar 28 '16 at 05:03
  • Anyway, I hope you got why I am telling to prefer translate3d. – Mr_Green Mar 28 '16 at 05:06
0

Use the following CSS to your 'childCont' class:

.childCont {
    position: fixed;
    width: 300px;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%,-50%, 0);
}
Mr_Green
  • 40,727
  • 45
  • 159
  • 271
Domain
  • 11,562
  • 3
  • 23
  • 44
  • I don't think `3D` is necessary here. – Mr_Green Mar 28 '16 at 04:52
  • It will take the div to the perfect center. – Domain Mar 28 '16 at 04:53
  • why is `top:50%`? – madalinivascu Mar 28 '16 at 04:53
  • 1
    @WisdmLabs I understand, I was actually trying to say to use `transform: translate(-50%, -50%)` instead of `transform: translate3d(-50%,-50%, 0)` but realized calling a 3d property must be preferred always. [link](http://stackoverflow.com/q/22111256/1577396) – Mr_Green Mar 28 '16 at 04:55
  • @madalin div is pos fixed and need to move to the center thats why left and top should be 50% – Domain Mar 28 '16 at 04:58
  • and also I prefer using `bottom` and `right` properties instead of `top` and `left` because of bug in IE10(_annoying vertical scroll, with some other css properties_) and no need to mention negative operand. – Mr_Green Mar 28 '16 at 04:58
0

You can use top:50% and right: 50%

Z3N1X
  • 47
  • 8
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 14 '22 at 15:43