0

Is it possible to center an absolute position div within a relative dive with margin 0 auto?

HTML:

<div class="outer">
  <div class="inner"></div>
</div>

CSS:

.outer{
  background: red;
  margin: 0 auto;
  width:100px;
  height:100px;
}

.inner{
  position:absolute;
  width:20px;
  height:20px;
  background:blue;
  top:10px;
  left:10px;
}

I was hoping that the absolute positioning would work within the outer one ok but I guess the margin. The above code can be seen here: http://jsfiddle.net/g4y4czff/

Ideally I'd like to use css to solve this but I reckon there's more likely to be a js solution.

Any ideas greatly appreciated.

C

AmanVirdi
  • 1,667
  • 2
  • 22
  • 32
Cathal
  • 1,740
  • 18
  • 31
  • possible duplicate of [How to center absolute element in div?](http://stackoverflow.com/questions/1776915/how-to-center-absolute-element-in-div) – Casey Falk Aug 13 '14 at 14:31

2 Answers2

2

New fiddle: http://jsfiddle.net/g4y4czff/1/

Just add position: relative to .outer

Reason is because the default position property is static

Benjamin
  • 2,612
  • 2
  • 20
  • 32
Populus
  • 7,470
  • 3
  • 38
  • 54
0

since you wanted it centered, here you have it centered horizontally and vertically too. Placing position:absolute; inside position:relative; allows it to be inside of it.

http://jsfiddle.net/g4y4czff/3/

.outer{
    background: red;
    margin: 0 auto;
    width:100px;
    height:100px;
    position:relative;
}

.inner{
    position:absolute;
    width:20px;
    height:20px;
    background:blue;
    top:0;
    margin: auto;
    left:0;
    right:0px;
    bottom:0;
}
Grasper
  • 1,293
  • 12
  • 26