【问题标题】:How to center align two divs having a parent div如何居中对齐具有父 div 的两个 div
【发布时间】:2014-08-30 23:52:49
【问题描述】:

如果我在父 div 中有两个 div,并且所有三个 div 都向左浮动。我所要做的就是将两个子 div 居中对齐而不移除左浮动。

【问题讨论】:

  • 你能提供你的html/css吗?
  • 所有三个 div 表示这些 div 是子 div?
  • 请将您的代码放入jsfiddle.net

标签: html css


【解决方案1】:

在子 div 上使用 display: inline-block 而不是 float: left,您可以将 text-align: center 分配给父 div。

【讨论】:

  • 使用 vertical-align: top 如果内联块 div 没有正确对齐
【解决方案2】:

让我看看我是否理解,所以你有这样的东西:

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

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

</div>

如果我是对的,你希望两个 div 子元素在父 div 的中心对齐,但不删除它们的左浮动。那么我认为这可能有效:

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

所以在 div 样式中,尝试通过向左分配一个百分比或像素值来使其居中: 它应该可以工作。我还建议你使用百分比,但首先使用像素来了解它是如何工作的。另一个建议是不要在 html 标签中使用 css,我只是向你展示了该怎么做,但建议使用另一个文件( style.css) 包含在您的 html 文件中。

【讨论】:

    【解决方案3】:

    此布局可能对您有所帮助:

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

    如果你想居中父 div 然后使用 margin:0 auto; 并删除 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%;}
      

      以百分比设置您的孩子宽度与边距。 它会将两个子 div 居中对齐

      【讨论】:

        【解决方案5】:

        您需要为 2 个子 div 设置这些样式:

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

        和父 div:

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

        注意:高度样式是可选的。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-11-04
          • 1970-01-01
          • 2011-03-13
          • 2016-08-17
          相关资源
          最近更新 更多