如何通过CSS在一行中的框之间创建相等的空间

时间:2014-06-25 07:08:15

标签: css

我要求一行有4个盒子。

  1. 盒子有宽度和高度固定
  2. 但行的宽度将根据屏幕尺寸而变化。
  3. 第一个框应该与行的左边框对齐
  4. 最后一个框与右边框对齐。
  5. 任何两个方框之间的空格也应该相等。
  6. 是否有纯CSS方法可以实现这一目标?这是jsfiddle code

    HTML:

    <div class="row">
        <div class ="col">
            <div class="box"></div>
        </div>
        <div class ="col">
            <div class="box"></div>
        </div>
        <div class ="col">
            <div class="box"></div>
        </div>
        <div class ="col">
            <div class="box"></div>
        </div>
    </div>
    

    CSS:

    .row {
        display: table;
        border: 1px solid green;
        width: 400px; /* it changes by screen size actually */
        padding: 5px;
    }
    .row:before, .row:after {
        content: "";
    }
    .row:after {
        clear: both;
    }
    .col {
        float: left;
        width: 25%;
    }
    .box {
        border: 1px solid #DDD;
        width: 80px;
        height: 80px;
        margin: 0 auto;
    }
    .col:first-child .box {
        margin-left: 0;
    }
    .col:last-child .box {
        margin-right: 0;
    }
    

4 个答案:

答案 0 :(得分:6)

在容器上使用text-align:justify,无论你在div中有多少元素,它都会有效(你不需要为每个列表项计算%width

更新了CSS

.row {
    text-align: justify;
    min-width: 412px;
    border: 1px solid green;
    width: 80%; /* it changes by screen size actually */
    height: 90px;
    padding: 5px;
}

.row:after {
    content: '';
    display: inline-block;
    width: 100%;
}
.col {
    display: inline-block;
}
.box {
    border: 1px solid #DDD;
    width: 80px;
    height: 80px;
    margin: 0 auto;
}

<强> FIDDLE

答案 1 :(得分:2)

您可以在现代浏览器中使用css3 flex boxes supported

HTML

<div class="row">
 <div class="box"></div>
 <div class="box"></div>
 <div class="box"></div>
 <div class="box"></div>
</div>

CSS

.row {
 display: flex;
 justify-content:space-between;
 ...
}

Demo

有关弹性框@ css tricks

的更多信息

答案 2 :(得分:0)

为什么不使用flexbox?

<强> Demo

CSS

.flex-container {
  padding: 5px;
  margin: 0;

  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;

  -webkit-flex-flow: row wrap;
  justify-content: space-between; /* this make the end divs at sides and equal space between other divs */
}

.flex-item {
  background: tomato;
  padding: 5px;
  width: 200px;
  height: 150px;
  margin-top: 10px;

  line-height: 150px;
  color: white;
  font-weight: bold;
  font-size: 3em;
  text-align: center;
}

HTML

<div class="flex-container">
  <div class="flex-item">1</div>
  <div class="flex-item">2</div>
  <div class="flex-item">3</div>
  <div class="flex-item">4</div>
</div>

Read here for more detail on flexbox

答案 3 :(得分:0)

您只需从以下

中删除padding属性即可
.row {
display: table;
border: 1px solid green;
width: 400px; /* it changes by screen size actually */
/*padding: 5px;*/
}

here is the demo.

请告诉我这是否有用,或者如果您有任何疑问。