2013-05-03 116 views
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; 
} 

回答

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; 
} 
+0

这个工作了伟大的,谢谢 – Benjamin 2013-05-10 01:23:54

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英寸之间,该容器宽度的内容宽度匹配。我不确定这是否是你想要的,但这可能是你能做的最好的。

你可以看到显示窄体和宽含量的样品,和造型更紧密地匹配this codepen你原来的例子扩展的例子。