Hussain Nayani
Hussain Nayani

Reputation: 21

How to center align two divs having a parent div

If I am having two divs in a parent div and and all three divs have float left. What I have to do is to align center the two child divs without removing float left.

Upvotes: 2

Views: 2566

Answers (5)

Anonymous
Anonymous

Reputation: 10216

This layout may help you:

HTML

<div class="div-p">
    <div class="div-1"></div>
    <div class="div-2"></div>
</div>

CSS - DEMO

.div-p{background-color:#eee;width:640px;height:400px;float:left;}
.div-1{background-color:#f00;width:300px;height:300px;float:left;margin:10px;}
.div-2{background-color:#0f0;width:300px;height:300px;float:left;margin:10px;}

If you want to center the parent div then use margin:0 auto; and remove the float:left;

CSS - DEMO

.div-p{background-color:#eee;width:640px;height:400px;margin:0 auto;}
.div-1{background-color:#f00;width:300px;height:300px;float:left;margin:10px;}
.div-2{background-color:#0f0;width:300px;height:300px;float:left;margin:10px;}

Upvotes: 1

Aida.Mirabadi
Aida.Mirabadi

Reputation: 1046

you need set these styles for 2 child divs :

{ width:50%; text-align:center; float:left; height:50px;}

and the parent div :

{ width:100%; margin: 0 auto; float:left; height:50px;}

Note: height style is optional.

Upvotes: 0

Petru Lebada
Petru Lebada

Reputation: 1682

Let me see if i have understood,so you have something like this:

<div id="parent" style="float:left;">

<div id="child1" style="float:left;"></div>
<div id="child2" style="float:left;"></div>

</div>

And if im right you want the two div childs to be aligned in the center of the parent div but without removing the left float of none of them.Then i think this might work:

<div id="parent" style="float:left;position:absolute;">

<div id="child1" style="float:left; position:relative; left: 100px"></div>
<div id="child2" style="float:left; position:relative; left: 100px"></div>

</div>

So in the div style,try to center it by assigning a value in percentage or pixels to left: It should work.I also advice you to use percentage,but first use pixels to understand how it works.And another advice is to not use css in html tags,i just showed you what to do,but it's recommended to have another file (style.css) to include in your html file.

Upvotes: 0

Ankur Kumar
Ankur Kumar

Reputation: 455

#parent{width:100%;}
#child1,#child2{width:90%;margin:0px 5%;}

set your child width in percentage with margin. it will align both child div in center

Upvotes: 0

moonwalker
moonwalker

Reputation: 1177

Use display: inline-block instead of float: left on child divs and you can give text-align: center to the parent div.

Upvotes: 1

Related Questions