我怎样才能创建左和右右侧固定宽度的元素,其中心填充其余部分?

时间:2015-07-31 09:43:49

标签: html css3

使用纯CSS我想知道如何在容器的两侧创建两个固定宽度的元素,其中心元素填充剩余的空间,如下所示:

enter image description here

“播放”和“全屏”图标以固定宽度连接到容器的侧面,但中心元素(在两个按钮之间缩放的红色条)应填充剩余空间。这似乎很难。

在SO上有一个相关的流行问题可以证明这一点,除了一侧只有一个固定宽度的元素:

How to make a div to fill a remaining horizontal space (a very simple but annoying problem for CSS experts)

如何做到这一点?

2 个答案:

答案 0 :(得分:3)

您可以像这样使用calc()

* {
  margin: 0;
  padding: 0;
}
.wrap {
  width: 100%;
}
.one {
  width: 100px;
  background: red;
  float: left;
}
.two {
  width: calc(100% - 200px);
  background: green;
  float: left;
}
<div class="wrap">
  <div class="one">left section</div>
  <div class="two">mid section</div>
  <div class="one">right section</div>
</div>

答案 1 :(得分:1)

灵活的盒子技术很容易解决这个问题。

  1. 将父容器设置为灵活框。
  2. 使用flex: 0 0 100px
  3. 将左右元素定位为固定宽度
  4. 使用flex: 1 1 auto
  5. 将中心元素定位为具有灵活宽度

    在此处详细了解这些属性:Guide to flexbox

    检查浏览器兼容性表:Flexbox

    * {
      margin: 0;
      padding: 0;
    }
    .container {
      display: flex;
      flex-flow: row nowrap;
    }
    .left,
    .right {
      background: lightblue;
      flex-shrink: 0;
      /* Don't shrink */
      flex-grow: 0;
      /* Don't grow */
      flex-basis: 100px;
      /* Set 100px as fixed width */
      /* flex: 1 1 auto; Short hand for above three properties */
      text-align: center;
    }
    .center {
      background: tomato;
      color: #fff;
      flex-shrink: 1;
      /* Shrink when resized */
      flex-grow: 1;
      /* Grow when resized */
      flex-basis: auto;
      /* Automatic width */
      /* flex: 1 1 auto; Short hand for above three properties  */
      text-align: center;
    }
    <div class="container">
      <div class="left">Left</div>
      <div class="center">Center</div>
      <div class="right">Right</div>
    </div>