2

#fit并根据情况说明我希望对一个元素#wrap具有的两种不同行为。该元素应该像有空间时那样工作,但应该像没有足够空间时那样工作。#fit#wrap

http://jsfiddle.net/benstenson/dN8VJ/

<div id="print">
    Printable
</div>
<div id="fit">
    Looks good on same line
</div>
<div id="wrap">
    Looks good on new line
</div>

css

body{overflow:hidden;padding:1em;}
div
{
    /*display:inline-block;*/
    float:left;
    height:1in;
    margin:.5em;text-align:center;line-height:1in;
    white-space:nowrap;box-shadow:0 0 .5em gray;
}
#print
{
    width:5in;
    background-color:black; color:white;
}
#fit
{
    /* when on same line
       Size to min-width
       OR fill remaining space
       (like flexible box style).
       Either way is fine.
    */
    min-width:3in;
    background-color:gold;
}
#wrap
{
    /* when wrapped to next line */
    /* fill 100% OR to max width */
    width:100%;
    min-width:3in;
    max-width:5in;
    background-color:orange;
}
4

2 回答 2

2

您正在寻找的Flexbox,但大多数支持 Flexbox 的浏览器支持换行。支持的有 IE10、Chrome 和 Opera。

http://codepen.io/cimmanon/pen/lqrGB

<div class="container">
  <div id="print">
    Printable
  </div>
  <div id="either">
    Looks good on either line
  </div>
</div>

.container {
  display: -ms-flexbox;
  display: -webkit-flex;
  -webkit-flex-wrap: wrap;
  -ms-flex-wrap: wrap;
  flex-wrap: wrap;
}
@supports (flex-wrap: wrap) {
  .container {
    display: flex;
  }
}
.container div {
  height: 1in;
  margin: .5em;
  text-align: center;
  line-height: 1in;
  white-space: nowrap;
  box-shadow: 0 0 .5em gray;
}

#print {
  /*-webkit-flex: 1 5in;
  -ms-flex: 1 5in;
  flex: 1 5in;*/
  width: 5in;
  background-color: black;
  color: white;
}

#either {
  -webkit-flex: 1 3in;
  -ms-flex: 1 3in;
  flex: 1 3in;
  max-width: 5in;
  background-color: gold;
}
于 2013-05-03T19:03:33.363 回答
1

假设我正确理解了您的问题,我认为您可以通过inline-block.

您需要将您的内容放在另一个 div 内的段落中,如下所示:

<div class="wrap-or-fit">
  <p>This is where your content goes.</p>
</div>

然后只需在段落上设置min-widthmax-width属性,以及display:inline-block.

.wrap-or-fit > p {
  max-width:5in;
  min-width:3in;
  display:inline-block;
  ...
}

如果内容适合小于 3 英寸宽的单行,则容器将扩展为至少 3 英寸。如果内容物的宽度超过 5 英寸,则强制将其包裹在正好 5 英寸的容器内。

如果内容在 3 到 5 英寸之间,则容器宽度与内容宽度匹配。我不确定这是否是你想要的,但这可能是你能做的最好的。

您可以在此 codepen中看到一个扩展示例,其中显示了窄内容示例和宽内容示例,以及与您的原始示例更匹配的样式。

于 2013-05-03T20:14:21.517 回答