Search code examples
csshtmlcenter

center a absolute positioned


I know how to center divs with CSS easily using position: relative; and margin:auto; , but i have a div that is supposed to be in front of all the other divs - so I set z-index: 1000; and position:absolute; . I can't figure out any other way to set this in front without position: absolute; if i try relative then it will go below everything else to the bottom. My question is how do I set this div that has z-index: 1000; position: absolute; to stay in the center?

I try left: 20%; which looks perfect , but when it is displayed on larger screens or much smaller screens obivously that percentage is not going to be the same.


Solution

  • You can do one of two things:

    1. give a fixed % width and do the math to center:

    position:absolute;width:60%;left:20% (100%-60% = 40% --> 40% / 2 = 20%)

    2 . position the div using position:absolute;text-align:center;, and give the inner elements position:relative;display:inline-block;