How to center align two divs having a parent div

不羁岁月 提交于 2021-02-19 08:43:09

问题


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.


回答1:


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




回答2:


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.




回答3:


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;}



回答4:


#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




回答5:


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.



来源:https://stackoverflow.com/questions/25443004/how-to-center-align-two-divs-having-a-parent-div

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!