Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何使用CSS使n列居中?_Css - Fatal编程技术网

如何使用CSS使n列居中?

如何使用CSS使n列居中?,css,Css,目前,我的4个专栏有以下CSS,将来可能会增加到5或6个: <style> .columns { margin: 0 auto; border: 1px red dotted; width: 90%; } .columns div { float: left; width: 20%; overflow:hidden; border: solid 1px; margin-right: 1em; } </style&

目前,我的4个专栏有以下CSS,将来可能会增加到5或6个:

<style>
.columns {
    margin: 0 auto;
    border: 1px red dotted;
    width: 90%;
}

.columns div {
    float: left;
    width: 20%;
    overflow:hidden;
    border: solid 1px;
    margin-right: 1em;
}
</style>

<div class="columns">
  <div>
    <h3>First</h3>
    <ul>
      <li>left</li>
    </ul>
  </div>
  <div>
    <h3>Second</h3>
    <ul>
      <li>mid</li>
    </ul>
  </div>
  <div>
    <h3>Third</h3>
    <ul>
      <li>right</li>
    </ul>
  </div>
  <div>
    <h3>Fourth</h3>
    <ul>
      <li>far right</li>
    </ul>
  </div>
</div>

.栏目{
保证金:0自动;
边框:1个红色点;
宽度:90%;
}
.栏目组{
浮动:左;
宽度:20%;
溢出:隐藏;
边框:实心1px;
右边距:1米;
}
弗斯特
第二
  • 中段
第三
第四
  • 极右翼

是否可以使用我所要的页面中间的所有4列?

你必须设置一个静态宽度。列:

.columns {
    width: 800px;
    margin-left: auto;
    margin-right: auto;
    border: 1px red dotted;
}
您可能还希望在文档底部(在.columns之后)放置一个clearing div:


这里唯一真正的秘密是取容器的总宽度除以四。在我提供的情况下,800/4=200,因此每列的总宽度(宽度+填充+边距)为200px

从技术上讲是的,但它要求您在某个点设置宽度,可能是在包装器div上。我不知道是否可以将动态宽度(即20%宽度)的浮动列居中。如果您将包装器div width设置为某个值,那么您可以在其他列上设置边距以使它们居中

我想在阅读了所有可能的答案后,我得到了一些可行的方法,其中包含了最少的硬编码计算值。为了简单起见,我去掉了边框:

.columns {
    position: relative;
    clear: both;
    margin: 0 auto;
    width: 900px;
}

.columns div {
    position: relative;
    float: left;
    width: 22%;
    overflow:hidden;
    margin-right: 4%;
}

.columns div.last {
    margin-right: 0;
}

在最后一列中使用

不要使用清除div。请使用“最小高度:10px”。f IE6即使内部的div浮动,min height是否会拉伸其容器div上的边框?第4列的右边缘和div.columns的右边框之间的间隙仍然存在。如何使4列均匀填充div.columns?更新了答案以解决此问题。要使旧版本的Internet Explorer中的div列居中,还需要使用文本对齐:居中;在列的父元素上。
.columns div {
    width: 160px;
    padding-left: 10px;
    padding-right: 10px;
    margin-left: 10px;
    margin-right: 10px;
}
.columns {
    position: relative;
    clear: both;
    margin: 0 auto;
    width: 900px;
}

.columns div {
    position: relative;
    float: left;
    width: 22%;
    overflow:hidden;
    margin-right: 4%;
}

.columns div.last {
    margin-right: 0;
}