34

I am trying to center an inline div in its parent. The parent element also has a child div that floats to the right. Because of the right aligned div, my centered div is shifted to the left. I want to center the middle div regardless of the position/size of the floating one like the image below with the code provided.

enter image description here

.parent {
    text-align: center;
}
.parent div {
    display: inline-block;
}
<div id="parent">
    <div> ... </div>
    <div style="float:right"> ... </div>
</div>

The current setup has both inner divs inside the parent but I'm assuming the right way is to have the right-aligned div be outside with an absolute position?

Also, I have multiple instances of the parent div on the same page.

How can I achieve this result?

TylerH
  • 20,799
  • 66
  • 75
  • 101
KDaker
  • 5,899
  • 5
  • 31
  • 44

2 Answers2

25

set the right div css

position:absolute;
right:0;

relative to the parent div

#parent {
position:relative;
}
KDaker
  • 5,899
  • 5
  • 31
  • 44
Sobin Augustine
  • 3,639
  • 2
  • 25
  • 43
  • this also requires setting parent's position to absolute – Bobo Aug 14 '13 at 19:22
  • If the right div doesn't have a max width (or a known width), content could be partially hidden under the other element. @Bobo relative is sufficient – FelipeAls Aug 14 '13 at 19:23
  • was also gonna answer, but would have been the same as this. Did create a fiddle though: http://jsfiddle.net/HjGrV/ – Tim Mac Aug 14 '13 at 19:28
4

position:absolute is the only way

DEMO http://jsfiddle.net/kevinPHPkevin/u4FWr/1/

.center {
    display:inline-block;
    position: absolute;
    left:0;
    right:0;
}

EDITED

not sure if this has already been suggested

Or you can absolute: position; the right div instead

DEMO http://jsfiddle.net/kevinPHPkevin/u4FWr/3/

.right {
    display:inline-block;
    position: absolute;
    right:0;
}
Kevin Lynch
  • 24,427
  • 3
  • 36
  • 37
  • is that the only way.? setting a left-margin to the middle div as same as the width of right div, then set middle div margin:auto.. is this a possible way.? – Sobin Augustine Aug 14 '13 at 19:32
  • That's a possible way but I wouldn't recommend it. Another way would be to set the right div to position absolute and locate it right, without floating and then center the other div accordingly. See my edit. – Kevin Lynch Aug 14 '13 at 19:37
  • ya and that what my answer is about. – Sobin Augustine Aug 14 '13 at 19:41
  • So the first solution doesnt really work because for some reason, the parent div ends up with 0 height. see [this](http://jsfiddle.net/kdaker/Kggnz/) . The second one works with the addition of 'position:relative' on the parent however Sobin already answered this before :) thank you though. – KDaker Aug 14 '13 at 19:53
  • Yeah @SobinAugustine did answer it first, It sounds like the best solution for your needs. – Kevin Lynch Aug 14 '13 at 19:58