I have a floated container with multiple child floated divs.
I want to center align (not text-align) all these floated child divs with respect to the floated container.
How do I do that ?
At a time, only 1 of these child div is visible on the browser ..User clicks on Prev/Next to view other child divs (kind of like Carousel)
Apparently I am facing issues center aligning if I use float:left for the child div.
You cannot align a floated element relative to a parent element.
float CSS property rips an element from its context in the document (similarly to
position:absolute/fixed). As a result of this, the element cannot be positioned "at the center of the parent".
Solution courtesy of: Rob W
I was searching for a solution today for my three divs inside a parent container and I came across this old post where a good solution doesn't seem to have been offered.
My situation: I have a parent container with width:100% so that it fits the screen. I also set a max-width so that the parent container doesn't grow too large. At the max-width I want the three child divs to display all in one row.
As the page is reduced and the parent container shrinks in width, I want the three child divs to reflow, each child div being pushed under the previous child div until they are all stacked vertically. As this happens I want the child divs to stay center aligned within the parent container.
The solution is to not use float which "rips an element from its context" as Rob W truly states, but instead use inline-blocks:
margin:0 auto; /*keep centered in page*/
width:100%; /*stretch to page*/
max-width:800px; /*expand up to 800px*/
text-align:center; /*keep my children centered*/
display:inline-block /*treat me as a block that flows like text*/
width:230px; /*set my size*/
vertical-align:top; /*keep me aligned at the top of my parent even if my siblings are taller than me*/
<div class='childDiv'>Content 1</div>
<div class='childDiv'>Content 2</div>
<div class='childDiv'>Content 3</div>
You can float the parent container, give it absolute positioning, pretty much whatever, and the child divs will keep their same behavior.
Discussion courtesy of: i_a
If you show only one child
div at once, probably they don't need to
float. The best way to center a non-floated block inside of another block is to assign the following style:
margin: 0 auto;
This will center the
div.child because both left and right margins will span equally to fit the parent container. Similarly, you can align
divs to the left and to the right:
Discussion courtesy of: Lapple
If you have a fixed width for both container and children, then you can use
margin-right set to (container div width - contained width width)/2. Of course, if you have paddings and borders, you have to account for them in the formula.
Discussion courtesy of: nikan
This recipe can be found in it's original form on Stack Over Flow.