【问题标题】:Div center issuediv中心问题
【发布时间】:2023-03-26 03:58:01
【问题描述】:

我有主容器 940 像素

主容器内有 2 个 div,每个宽度为 250 像素

我希望这些框与主容器居中对齐。但是问题是第二个 div 动态添加。因此,如果第二个 div 不存在,第一个应该居中。并且当添加第二个 div 时,两者都应按 940 px 主 div 居中。

我尝试了很多,但无法找到解决方案。请帮忙!

这里是简化的代码

CSS

   div.box {
    background: #EEE;
    height: 400px;
    width: 940px;
}
div.left {
    background: #999;
    float: left;
    height: 390px;
    width: 250px;
}
div.right {
    background: #666;
    height: 390px;
    width: 250px;
    float: left;
}
div.clear {
    clear: both;
}

HTML

 <div class="box">

       <div class="left">Tree</div>
       <div class="right">View</div> ( this div will dynamically add)
       <div class="clear" />

    </div>

谢谢

【问题讨论】:

  • 你的源代码在哪里?这里图片不显示
  • 我还不能发布图片,所以我编辑了我的 cmets。添加代码供参考。

标签: jquery css html center


【解决方案1】:

在你的 div.box css 中试试这个

 margin:0px auto;

对于演示,请查看JSFIDDLE DEMO

【讨论】:

    【解决方案2】:

    制作这个remove clear:both;

    http://jsfiddle.net/jWVxd/4/

    CSS

      div.box {
        width: 940px;
        background: #EEE;
        height: 400px;
        display: table;
        padding:10px;
    }
    div.left {
        background: #999;
        display: table-cell;
        width: 250px;
    }
    div.right {
        background: #666;
        display: table-cell;
        width: 250px;
    }
    

    【讨论】:

    • OP 想要 div 居中,检查了你的 Jsfiddle 它没有解决
    • 非常感谢。但是有没有解决方案可以让这段代码在 IE7 中运行。
    【解决方案3】:

    只需将margin:auto; 添加到您的div.box,它就会出现在中心

    JS FIDDLE DEMO

    已编辑: 这里隐藏了第二个 div (".right") 和它的工作正常

    2nd Demo 现在按 Ctrl-(减号)看到它在中心

    【讨论】:

    • 感谢您的回复。但是当您尝试删除第二个框时。第一个框不在您的示例中居中。
    猜你喜欢
    • 2012-09-14
    • 2020-03-04
    • 2013-05-04
    • 2016-12-18
    • 2016-12-25
    • 1970-01-01
    • 2016-10-21
    • 1970-01-01
    • 2020-02-24
    相关资源
    最近更新 更多