【问题标题】:problem with grid (Div)网格问题(Div)
【发布时间】:2011-08-01 10:02:57
【问题描述】:

我正在处理的网格有问题。基本上我正在使用 div 创建一个网格。所以你可以想象,有一个容器 div 填充了行和单元格。我似乎能弄清楚的是如何使细胞居中。对于我的容器 div,我使用了具有固定宽度的自动左右边距,如下所示。

#container {
     margin: 0 auto;
     width:960px;
} 

#container .row { 
    height: 220px; 
    margin-bottom:20px; 
} 

#container .row .cell { 
    float: left; 
    margin: 0 20px 20px 20px; 
    height: 170px; 

}

这看起来不错,但我想要的是让容器中的 div 居中,例如,如果我在容器 div 中只有一个单元格(div),它应该在容器 div 中居中.

【问题讨论】:

  • 你为什么不使用表格?这就是它们存在的原因。
  • 我知道,但考虑到可访问性时,使用表格并不是最佳选择。

标签: html css xhtml


【解决方案1】:

不是浮动“单元格”,而是将它们变成内联块,然后它们会像文本一样居中

#container {
     margin: 0 auto;
     width:960px;
     border: 14px solid #000;
} 

#container .row { 
    height: 220px; 
    margin-bottom:20px; 
    background: #cfc;
    text-align: center; /** add this **/
} 

#container .row .cell { 
    /*float: left;*/  /* remove this */
    display: inline-block; /* add this */
    margin: 0 20px 20px 20px; 
    height: 170px; 
    background: #dad;
}


/* IE7 and below needs the following rule to make inline-block work on block level element - disclaimer: this is a hack you can put this in a conditional comment for `lte IE 7` without the '!ie7' bit if you don't like hacks */
#container .row .cell { display: inline !ie7;}

【讨论】:

  • +1,这是我刚刚完成的演示:jsfiddle.net/thirtydot/3yqUR 我正在回答的唯一其他文本是:“我假设您只是在使用命名错误的类,并且在这里使用表格实际上是错误的,因为它会使用表格进行布局。”
  • +1 同意您的补充,但我认为表格、行和单元格在这里永远困扰着我们,即使在描述布局时 - 我有时也会自己使用它们(在描述时!)eeek :)
  • 我怎么没想到呢?太好了,谢谢...解决了我的问题
  • @gables20 - 不客气 :)
【解决方案2】:

您不能将那个 div 居中,因为您在这里使用的是浮点数。

如果您将任何 div 向左或向右浮动

然后它不能移动到父 div 的中心。

如果你想创建网格,你也可以使用 span 或任何其他内联元素而不是块级元素

【讨论】:

    猜你喜欢
    • 2015-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-04
    • 1970-01-01
    相关资源
    最近更新 更多