五个(20%)相等的div在一行中具有20px的边距权利?

时间:2017-05-15 14:02:37

标签: html css html5 css3 twitter-bootstrap-3

如何在一行中获得5个(20%相等)浮动div,每个除了最后一个孩子之外,每个边距为20px?

结构:

<div class="f-item pull-left">1</div>
<div class="f-item pull-left">2</div>
<div class="f-item pull-left">3</div>
<div class="f-item pull-left">4</div>
<div class="f-item pull-left">5</div>

尝试使用以下内容,这会破坏行(并且最后一个孩子的“重置”似乎被忽略):

.f-item {
    margin-right: 20px;
    width: 20%;

    &:last-child {
        margin-right: 0;
    }
}

Fiddle示例。

.f-group {
  width: 100%;
}

.f-item {
  margin-right: 20px;
  width: 20%;
  background-color: green;
  text-align: center;
  color: white;
}

.f-item:last-child {
  margin-right: 0;
}

.col-sm-12 {
  background-color: red;
  padding: 0;
}
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare.com/ajax/libs/normalize/7.0.0/normalize.css" rel="stylesheet"/>
<div class="col-sm-12">
  <div class="f-group">
    <div class="f-item pull-left">
      1
    </div>
    <div class="f-item pull-left">
      2
    </div>
    <div class="f-item pull-left">
      3
    </div>
    <div class="f-item pull-left">
      4
    </div>
    <div class="f-item pull-left">
      5
    </div>
    <div class="clearfix"></div>
  </div>
  <div class="col-sm-12">

2 个答案:

答案 0 :(得分:1)

您需要调整项目宽度以允许边距宽度...

proc substituteInFile {variableValue fileName} {
    # Read
    set f [open $fileName]
    set data [read $f]
    close $f

    # Do substitution(s) in memory
    set myvariable $variableValue
    set data [subst $data]

    # Write
    set f [open $fileName "w"]
    puts -nonewline $f $data
    close $f
}

https://jsfiddle.net/7e1pdttt/1/

仅限CSS:

.f-item {
    width: calc(20% - 16px);
    margin-right: 20px;
    background-color: green;
    text-align: center;
    color: white;

    &:last-child {
        margin-right: 0;
    }
}

http://www.bootply.com/jxKTTBZsSi

答案 1 :(得分:1)

考虑flexbox

&#13;
&#13;
.f-items {
  display: flex;
  justify-content: space-between;
}

.f-item {
  margin-right: 20px;
  flex-wrap: nowrap;
  width: 100%;
  box-sizing: border-box;
  background: #eee;
}

.f-item:last-child {
  margin-right: 0;
}
&#13;
<div class="f-items">
  <div class="f-item pull-left">1</div>
  <div class="f-item pull-left">2</div>
  <div class="f-item pull-left">3</div>
  <div class="f-item pull-left">4</div>
  <div class="f-item pull-left">5</div>
</div>
&#13;
&#13;
&#13;