【问题标题】:Centering inside a div [duplicate]在 div 内居中 [重复]
【发布时间】:2013-03-27 03:09:12
【问题描述】:

可能重复:
How to center a div in a div?

我有一个大的 DIV,它的宽度和高度为 100%,因此它占据了整个浏览器。我里面还有另一个 DIV,宽度为 1024 像素,高度为 400 像素。我想知道将 div 水平和垂直居中的最佳方法是什么?我还希望它在调整浏览器大小时保持在中心。是否有 jQuery 插件,一些方便的 javascript,或者我可以简单地使用 CSS 来做到这一点。

标记

.bigdiv{
height:100%;
width:100%;
background-color:#eee;
}
.smalldiv{
height:400px;
width:1024px;
background-color:#ccc;
}

<div class="bigdiv">
<div class="smalldiv"></div>
</div>

感谢您的帮助和建议!

【问题讨论】:

  • 这个问题已经回答过很多次了。尝试在 Stack Overflow 中搜索。关键是position: absolutemargin-left: -width/2margin-top: -height/2,以及带有position: relative的容器。
  • @elclanrs 并添加 'top:50%;left:50%;'到小div
  • @gion_13:对!忘记了。
  • 谢谢大家,工作就像一种享受

标签: javascript jquery css


【解决方案1】:

尝试使用,margin:0 auto;

.smalldiv{
height:400px;
width:1024px;
background-color:#ccc;
margin:0 auto;
}

【讨论】:

    【解决方案2】:

    您可以轻松地将margin:auto; 提供给您的子 div 以获得您想要的结果

    HTML

    <div class="bigdiv">
    <div class="smalldiv"></div>
    </div>
    

    CSS

     .bigdiv{
        height:100%;
        width:100%;
        background-color:#eee;
        }
        .smalldiv{
        height:400px;
        width:1024px;
        background-color:#ccc;
        margin:auto;
        }
    

    DEMO

    【讨论】:

    • 您还必须将 html{height:100%;}body{height:100%;}​ 添加到 css。但它不起作用,因为边距自动在垂直方向上不起作用。使用我在下面发布的。
    【解决方案3】:

    好的,这就是让它居中的方法。

    .bigdiv{
    height:100%;
    width:100%;
    background-color:#eee;
    position:relative;
    }
    .smalldiv{
    height:400px;
    width:1024px;
    background-color:#ccc;
    position:absolute;
    left:50%;
    top:50%;
    margin-left:512px;
    margin-top:200px;
    }
    
    <div class="bigdiv">
    <div class="smalldiv"></div>
    </div>
    

    【讨论】:

      【解决方案4】:

      在较大的 div 中使用 text-align:centermargin:0 auto 在你的内部 div 中

      【讨论】:

        猜你喜欢
        • 2017-09-25
        • 2021-03-11
        • 1970-01-01
        • 2020-04-14
        • 1970-01-01
        • 1970-01-01
        • 2019-07-29
        • 2014-05-10
        • 2015-12-05
        相关资源
        最近更新 更多