center aligning a fixed position div

Solution 1:

Koen's answer doesn't exactly centers the element.

The proper way is to use CCS3 transform property. Although it's not supported in some old browsers. And we don't even need to set a fixed or relative width.

.centered {
    position: fixed;
    left: 50%;
    transform: translate(-50%, 0);
}

Working jsfiddle comparison here.

Solution 2:

For the ones having this same problem, but with a responsive design, you can also use:

width: 75%;
position: fixed;
left: 50%;
margin-left: -37.5%;

Doing this will always keep your fixed div centered on the screen, even with a responsive design.

Solution 3:

You could use flexbox for this as well.

.wrapper {
  position: fixed;
  top: 0;
  left: 0;
  height: 100%;
  width: 100%;
  
  /* this is what centers your element in the fixed wrapper*/
  display: flex;
  flex-flow: column nowrap;
  justify-content: center; /* aligns on vertical for column */
  align-items: center; /* aligns on horizontal for column */
  
  /* just for styling to see the limits */
  border: 2px dashed red;
  box-sizing: border-box;
}

.element {
  width: 200px;
  height: 80px;

  /* Just for styling */
  background-color: lightyellow;
  border: 2px dashed purple;
}
<div class="wrapper"> <!-- Fixed element that spans the viewport -->
  <div class="element">Your element</div> <!-- your actual centered element -->
</div>

Solution 4:

From the post above, I think the best way is

  1. Have a fixed div with width: 100%
  2. Inside the div, make a new static div with margin-left: auto and margin-right: auto, or for table make it align="center".
  3. Tadaaaah, you have centered your fixed div now

Hope this will help.