0

Here is the CSS:

#indicator {
  position: fixed;
  top: 40%;
  width: 150px;
  margin: 0 auto;
  z-index: 1000;
  padding: 2px;
  background: #fff;
}

Whenever I apply it, the content stays hard left, not centered. I have tried it with block elements (such as P and H1), and inline elements (such as span).

When I check the HTML inspector I can see that the rules are being applied as expected, and none are being overridden.

DatsunBing
  • 8,684
  • 17
  • 87
  • 172

4 Answers4

1

By default, margin auto wont work with fixed elements. To make the margin auto value work with fixed elements, add left:0 and right:0 to your CSS values. Attached a code snippet for your reference.

#indicator {
  position: fixed;
  top: 40%;
  left: 0;
  right: 0;
  width: 150px;
  margin: 0 auto;
  z-index: 1000;
  padding: 2px;
  background: red;
}
<div id="indicator">
</div>
amateur_me
  • 55
  • 6
0

Because margin:auto only works with position:relative.

To make a fixed div to work with margin:auto, add left: 0; right:0; to your div.

#indicator_relative {
  position: relative;
  margin: 0 auto;
  background: #0f0;
  width: 10px;
  height: 10px;
}

#indicator_fixed {
  position: fixed;
  margin: 0 auto;
  background: #f00;
  width: 10px;
  height: 10px;
}

#indicator_fixed_centered {
  position: fixed;
  margin: 0 auto;
  background: #00f;
  width: 10px;
  height: 10px;
  left:0;
  right:0;
}
<div id='indicator_fixed'></div>
<div id='indicator_relative'></div>
<div id='indicator_fixed_centered'></div>
rx2347
  • 1,071
  • 1
  • 6
  • 26
-1

To center fixed/absolute position elements. Add left: 50%; margin-left: (element width/ 2 * -1)px;

#indicator {
  position: fixed;
  top: 40%;
  width: 150px;
  margin: 0 auto;
  z-index: 1000;
  padding: 2px;
  background: #fff;

  left: 50%;
  margin-left: -75px; /* (element width / 2 * -1) */
}

plus make sure that the parent element where you want to center this, has position: relative; so it wont just fly around.

Markipe
  • 616
  • 6
  • 16
-1

top 40%; horizontal center;

#indicator {
  position: fixed;
  top: 40%;
  left: 50%;
  transform: translateX(-50%);
}
<div id="indicator">Hello World</div>

or center screen

#indicator {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
<div id="indicator">Hello World</div>
Cem PEHLIVAN
  • 141
  • 3