创建内部有两个div的div需要保持居中

时间:2014-02-11 15:52:00

标签: html css

我正在使网站响应,并且在主页上我应该插入两个应该居中并对齐的“容器”。 (在这种情况下,容器是两个带有内部图像和文本的div)

我希望他们会以这种方式行事

当页面被“限制”时,两个div应该以这种方式定位

我试过这样,但这不完全是我得到的

<div style="">
     <div style="width: 300px;float: left;">
        div 1
     </div>

     <div style="width: 300px;float: left;">
        div 2
     </div>
</div>

3 个答案:

答案 0 :(得分:2)

我尝试使用 display:inline-block 属性。通过这种方式,您不必为父级应用“溢出”,并且很容易使块居中。

HTML:

<div class="wrapper">
    <div class="box">Div 1</div>
    <div class="box">Div 2</div>
</div>

CSS:

.wrapper {
    text-align: center;

    /* Just decoration */
    border: 1px solid blue;
    padding: 20px;
}
.wrapper .box {
    display: inline-block;
    width: 300px;
    height: 50px;

    /* Just decoration */
    border: 1px solid green;
}

看看小提琴http://jsfiddle.net/caprella/y4BQ3/

答案 1 :(得分:1)

我为你准备了一些东西。您希望样式切换时,必须使用媒体查询来查找页面的大小。用我的例子搞清楚,你应该能够根据自己的喜好找出一些东西。

<div id="box">
     <div class="innerBox">
        div 1
     </div>

     <div class="innerBox">
        div 2
     </div>
    <div class="clear"></div>
</div>

CSS ......

#box {
    width:88%;
    background:red;
    padding:20px 6%;
}
.clear{clear:both}
.innerBox {
    width:41%;
    float:left;
    background:blue;
    display:block;
}
.innerBox:first-child {
    margin-right:18%;
}
@media screen and (max-width: 400px) {
    #box .innerBox {
        float:none;
        width:100%;
        margin:20px 0 0 0;
    }    
    #box .innerBox:first-child {
        margin-top:0;
    }
}
  }

JsFIddle链接:http://jsfiddle.net/x3JLX/

答案 2 :(得分:0)

看看这个小提琴。您现有的代码只有一些简单的更改,我在下面包含这些更改。 http://jsfiddle.net/ArKKG/

<div style="overflow:auto; height: 100% text-align: center;">
    <div style="width: 300px; height: 50px;float: left;">
       div 1
    </div>

    <div style="width: 300px;height: 50px;float: left;">
       div 2
    </div>
</div>

还有一些CSS可以让它们可见,并保持边框分离。

div{
    border: 1px solid black;
    margin: 4px;
}
相关问题