Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Center align multiple child DIV

Tags:

css

css-float

I am finding it bit confusing working around this problem.

I have parent DIV and 3/more Child DIV.

Parent DIV is center aligned and child DIV should be floating left but should be aligned center.

CSS contains,

.center {
   float:left;
   height:250px;
   width:15%;
   margin: 0 auto;
   border: 1px solid black;
}

I have a sample of the code link here...

like image 231
Santosh Avatar asked Nov 28 '12 10:11

Santosh


People also ask

How do I center multiple divs in a div?

Simply place margin:auto; for all subsequent divs inside your main wrapper that is text-align:center; .

How do you align all elements to the center of a child?

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 you center div children?

To truly center the child div, you can set negative top and left margins. Each value should be exactly half the child element's height and width.


2 Answers

If you want to horizontally align your elements centrally, then don't float them.

Change the way they are displayed to inline-block and align them in the center by changing the text-align style of their parent:

#parent {
    text-align:center;
    height:450px;
    width:75%;
    border:1px solid blue;
}
.center {
    display:inline-block;
    height:250px;
    width:15%;
    margin: 0 auto;
    border: 1px solid black;
}
<div id="parent">
    <div id="child1" class="center"></div><!--
 --><div id="child2" class="center"></div><!--
 --><div id="child3" class="center"></div>
</div>

Be sure to have no white-space or newlines between your children <div>s (in your HTML, that is) or comment it out. Now that these are inline elements, this white-space will be interpreted as a space.

like image 83
George Avatar answered Sep 25 '22 08:09

George


#parent{
    display: flex;
    justify-content:center;
    flex-direction:row; /*default value is row*/
    height:350px;
    width:75%;
    border:1px solid blue;
    padding: 10px 0;/* not mandatory */
}
.center {
    height:250px;
    width:15%;
    margin:5px;
    border: 1px solid black;
}
<div id="parent">
<div id="child1" class="center">
</div>
    <div id="child2" class="center">
</div>
    <div id="child3" class="center">
</div>
</div>

Flex helps us achieve certain things with ease.

like image 39
Harsha Vardhan Chakka Avatar answered Sep 25 '22 08:09

Harsha Vardhan Chakka