代码之家  ›  专栏  ›  技术社区  ›  Sruly

如何使div居中并围绕其内部的div展开?

  •  5
  • Sruly  · 技术社区  · 17 年前

    我有一个我想要居中的页面,在整个内容周围有一个背景和边框。

    我发现了一个javascript黑客使它成为中心,但它只在页面加载后才中心,看起来很糟糕。

    下面是一个示例html页面,它分享了我的问题

    <div style="background-color: Red; width: 980px; position: absolute;" id="container">
        <br />
        <br />
        <br />
        <br />
        <div style="width: 400px; background-color: Black; float: left;">
            <br />
            <br />
        </div>
        <div style="width: 400px; background-color: Blue; float: left;">
            <br />
            <br />
        </div>
    </div>
    

    下面是使其工作的Javascript(使用Jquery)

    $(function() {
            var winH = $(window).height();
            var winW = $(window).width();
            $("#container").css('left', winW / 2 - $("#container").width() / 2);
        });
    

    一定有更好的办法。

    谢谢

    4 回复  |  直到 17 年前
        1
  •  8
  •   Guffa    17 年前

    使用 auto 左右 margin

    在浮动元素之后放置一个元素并使用 clear 把它放在他们下面。因为它不是浮动的,所以会影响外部div的大小。

    <div style="margin: 0 auto; background-color: Red; width: 980px;" id="container">
        <br />
        <br />
        <br />
        <br />
        <div style="width: 400px; background-color: Black; float: left;">
            <br />
            <br />
        </div>
        <div style="width: 400px; background-color: Blue; float: left;">
            <br />
            <br />
        </div>
        <div style="clear: both; height: 0; overflow: hidden;"></div>
    </div>
    
        2
  •  0
  •   simon622    17 年前

    这是一个棘手的问题,但我在样式表中使用以下代码:;

    <style>div.sentor {text-align: center; height: 100%;} div.child{margin-left: auto; margin-right: auto; width: 95%; height: 100%;}</style>
    

    然后在体内;

    <div class="sentor">
    <div class="child">
        <div id="mycontent">
    

    这应该能奏效

        3
  •  0
  •   Emily    17 年前

    使用:

    <div style="margin:0 auto; overflow:hidden; background-color: Red; width: 980px; id="container">
    

    保证金:0自动;将使红色分区居中。

    溢出:隐藏;将使红色div拉伸以包含两个浮动div。

        4
  •  0
  •   Andrew Noyes    17 年前

    <html>
        <head>
            ...
        </head>
    
        <body>
    
            <div id="center">
                <!-- your content -->
            </div>
    
        </body>
    
    </html>
    

    要使div#center的内容移动到页面的中心,我们需要以下CSS:

    body {
        text-align: center;
    }
    
    div#center {
        text-align: left;
        width: 600px;    // Or some other arbitrary width
        margin: 0 auto;
    }
    

    这将使身体内的一切处于中心。但是,文本对齐:居中;属性也将应用于body的子级,所以我们使用第二个样式规则来取消它。或者,可以使用以下样式规则代替div#center:

    body * {
        text-align: left;
    }