-1

Playing around with some absoloute divs I have in my header. logo, search bar etc and trying to get them centered.

Will margin: 0 auto; ever work with an element set as absolute?

I know of some options to center divs within a 100% width such as calc, transform, flex. Are there any more centering 100% options?

Molder
  • 121
  • 8
  • Try to add `left:0;` and `right:0;` and please, post your completed code. – Alex Dec 03 '15 at 14:15
  • Hard to work out exactly what you mean, but you may be interested in `box-sizing`: http://learnlayout.com/box-sizing.html – Shameen Dec 03 '15 at 14:17

1 Answers1

1

Yes, it will work if the element is positioned correctly and has a width specified.

In the example below, left: 0/right: 0 is added so that the element is centered relative to the parent. For instance:

.container {
  position: relative;
}
.absolute {
  position: absolute;
  width: 80%;
  height: 40px;
  background-color: #000;
  margin: 0 auto;
  left: 0;
  right: 0;
}
<div class="container">
  <div class="absolute"></div>
</div>

Alternatively, you can also use a combination of left: 50%/transform: translateX(-50%) in order to center the element horizontally.

.container {
  position: relative;
}
.absolute {
  position: absolute;
  width: 80%;
  height: 40px;
  background-color: #000;
  left: 50%;
  transform: translateX(-50%);
}
<div class="container">
  <div class="absolute"></div>
</div>
Josh Crozier
  • 233,099
  • 56
  • 391
  • 304