【问题标题】:3 Fluid Divs width 2 Fixed Margins between them?3 Fluid Divs 宽度 2 它们之间的固定边距?
【发布时间】:2015-02-07 03:51:30
【问题描述】:

我有以下设置,但是将 div 的宽度设置为 30% 左右并不能始终如一地工作(一旦窗口宽度小于某个数字,第三个 div 就会低于..

有没有更好的方法来做到这一点,让我的 div 始终保持内联并越来越小,而它们之间的边距保持固定在 18px?

CSS:

.parent {
  width: 100%;
  height: 50px;
}  

.child {
  float: left;
  margin-right: 18px;
  border: 2px solid white;
  text-align: center;
  line-height: 50px;
  height: 100%;
  width: ~30%; /* doesn't work */
}  

.child:nth-child(3) {
  margin-right: 0;
}

HTML:

<div class="parent">
  <div class="child">one</div>
  <div class="child">two</div>
  <div class="child">three</div>
</div>

【问题讨论】:

    标签: css margin grid-layout fluid-layout fixed-width


    【解决方案1】:

    如果您正在寻找 IE8 支持,并且可以更改您的标记,您可以将块嵌套在 33.33% 宽度的元素内。

    对于IE8的支持,你需要get rid of the nth-child()声明。为了只有内部间隙,我使用了这里描述的技术:Items grid with inner padding only

    DEMO

    body{
        overflow:hidden;
        margin:0;
    }
    .wrap{
        margin: 0 -9px;
    }
    .box {
        width:33.33%;
        float:left;
    }
    .box div {
        background:grey;
        height:150px;
        margin:0 9px;
    }
    <div class="wrap">
        <div class="box">
            <div>one</div>
        </div>
        <div class="box">
            <div>two</div>
        </div>
        <div class="box">
            <div>three</div>
        </div>
    </div>

    【讨论】:

      【解决方案2】:

      使用calc() 计算列宽。

      .child {width: calc(33.333% - 12px);} /* margins in total have 36px / 3 cols  */
      

      Calc 从 IE9 开始支持。

      【讨论】:

      • IE8+ 的任何解决方案?
      • @SproutCoder:不,只有使用百分比边距的解决方案(例如,对 IE8 使用 cond.comment)。在您的主样式表中,您可以拥有calc,并且在该链接下,仅适用于 IE8 的样式表被覆盖marginwidth.child