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.
.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?
Inline block divs can be centered by applying text-align:center to their parent.
Like last time, you must know the width and height of the element you want to center. Set the position property of the parent element to relative . Then set the child's position property to absolute , top to 50% , and left to 50% . This just centers the top left corner of the child element vertically and horizontally.
After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property. Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements.
set the right div css
position:absolute; right:0;
relative to the parent div
#parent { position:relative; }
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With