如何以一个中间块始终为全宽的方式将三个内容块放在一行中?

时间:2015-02-08 03:09:57

标签: html css

我有三个内容块,我想以一种中间块始终为全宽的方式进行内联(填充第一个块和第三个块之间100%的空间)。

如何使用HTML和CSS实现这一目标?

.row {
  border: 1px solid black;
  padding: 1px;
}
.one {
  border: 1px solid red;
  display: inline-block;
}
.two {
  border: 1px solid yellow;
  display: inline-block;
}
.three {
  border: 1px solid blue;
  display: inline-block;
  float: right;
}
<div class='row'>
  <div class='one'>One</div>
  <div class='two'>Two</div>
  <div class='three'>Three</div>
</div>

1 个答案:

答案 0 :(得分:2)

  • 方法1

    将父元素的display设置为flex,并将flex-grow: 1添加到中间元素:

    &#13;
    &#13;
    .row {
        border: 1px solid black;
        padding: 1px;
        display: flex;
        text-align: center;
    }
    .one {
        border: 1px solid red;
    }
    .two {
        border: 1px solid yellow;
        flex-grow: 1;
    }
    .three {
        border: 1px solid blue;
    }
    &#13;
    <div class='row'>
        <div class='one'>One</div>
        <div class='two'>Two</div>
        <div class='three'>Three</div>
    </div>
    &#13;
    &#13;
    &#13;


  • 方法2

    将父元素的display设置为table,将子元素display设置为table-cell。然后将中间元素的宽度设置为100%

    &#13;
    &#13;
    .row {
      border: 1px solid black;
      padding: 1px;
      display: table;
      width: 100%;
      text-align: center;
    }
    .row > div {
      display: table-cell;
    }
    .one {
      border: 1px solid red;
    }
    .two {
      border: 1px solid yellow;
      width: 100%;
    }
    .three {
      border: 1px solid blue;
    }
    &#13;
    <div class='row'>
        <div class='one'>One</div>
        <div class='two'>Two</div>
        <div class='three'>Three</div>
    </div>
    &#13;
    &#13;
    &#13;


  • 方法3 (中间元素赢了但不填补剩余空间)

    将第一个元素浮动到左侧,将第三个元素浮动到右侧,并使用父元素上的text-align: center将中间元素居中:

    &#13;
    &#13;
    .row {
      border: 1px solid black;
      padding: 1px;
      text-align: center;
    }
    .one {
      border: 1px solid red;
      float: left;
    }
    .two {
      border: 1px solid yellow;
      display: inline-block;
    }
    .three {
      border: 1px solid blue;
      float: right;
    }
    &#13;
    <div class='row'>
      <div class='one'>One</div>
      <div class='two'>Two</div>
      <div class='three'>Three</div>
    </div>
    &#13;
    &#13;
    &#13;