如何在div中居中div组?

时间:2014-11-24 17:04:23

标签: html css css3

我是一个CSS的新手,我很混淆试图将一组div放在div中。我想要的是什么:

div 2,3和4应该在div1中居中。

我的方法:

.div1 {
    display: inline-block;
    margin: 0 auto;
    text-align: center;
}

.restofdivs {
    width: 470px;
    margin: 20px;
    min-height: 1px;
    float:center
}

结果是:3个div(2,3和4)一个在另一个上面......

此致

3 个答案:

答案 0 :(得分:1)

可能在.div1上设置宽度并从.div1

中删除内联块
.div1 {
  width: 960px;
  margin: 0 auto;
  text-align: center;
}

.restofdivs {
  width: 470px;
  margin: 20px;
  min-height: 1px;
 }

答案 1 :(得分:1)

这可以通过表格显示轻松完成:

.table-display {
  display: table;
  width: 100%;
}
.cell-display {
  display: table-cell;
}
.div1, .div2, .div3, .div4 {
  padding: 40px;
}
.div1 {
  background: #ABC;
}
.div2 {
  background: #DEF;
}
.div3 {
  background: #CAD;
}
.div4 {
  background: #FAD;
}
<div class="div1">
  <div class="table-display">
    <div class="cell-display div2"></div>
    <div class="cell-display">
      <div class="div3"></div>
      <div class="div4"></div>
    </div>
  </div>
</div>

答案 2 :(得分:0)

如果您知道块元素的宽度,则最常用的方法是定义宽度并使用&#34; margin:0 auto&#34;。这告诉浏览器给出上下边距为0,并自动确定左右边距相等。

使用浮动,您可以创建如下所述的布局:

http://jsfiddle.net/ynt4suee/

标记:

<div>
<div id="one" class="border clearfix">one
    <div id="wrapper">
        <div id="two" class="border">two</div>
        <div class="subcontainer">
            <div id="three" class="border">three</div>
            <div id="four" class="border">four</div>
        </div>
    </div>
</div>  

CSS:

div.border{
border: 1px solid red;
}

div#wrapper{
width: 400px;
margin: 0 auto;
}

div#two{
width: 250px;
float: left;
}

div.subcontainer{
float: right;
width: 130px;
}

.clearfix:after {
content: " "; /* Older browser do not support empty content */
visibility: hidden;
display: block;
height: 0;
clear: both;
}

这是另一种方法,使用内部div的内联块元素代替:

http://jsfiddle.net/xojqq4v5/

标记:

<div id="one" class="border">
div 1
<div id="wrapper">
    <div id="two" class="border">div 2</div>
    <div id="subcontainer">
        <div id="three" class="border">div 3</div>
        <div id="four" class="border">div 4</div>
    </div>
</div>
</div>

CSS:     div.border {     边框:1px纯红色;     margin-bottom:5px;     }

div#wrapper{
width: 450px;
margin: 0 auto;
}

div#two, div#subcontainer{
display: inline-block;
vertical-align: top;
}

div#two{
width: 300px;
}

div#three, div#four{
width: 140px;
}

尽管如此,只要知道内部div的总宽度,就可以使用&#34; margin:0 auto&#34;将包装器居中,这样做的好处是不会在所有子元素上居中,除非另有说明指定。

这里的区别在于,在列中布置内部div,div 2和包含div 3和4的容器div被定义为内联块元素。