Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center inline-block div in parent while ignoring floating elements

Tags:

html

css

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?

like image 837
KDaker Avatar asked Aug 14 '13 19:08

KDaker


People also ask

How do I center an inline block?

Inline block divs can be centered by applying text-align:center to their parent.

How div align child div in center of 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.

How do I center a div with a display block?

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.


2 Answers

set the right div css

position:absolute; right:0; 

relative to the parent div

#parent { position:relative; } 
like image 117
Sobin Augustine Avatar answered Oct 14 '22 05:10

Sobin Augustine


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; } 
like image 33
Kevin Lynch Avatar answered Oct 14 '22 06:10

Kevin Lynch