【问题标题】:How can I use CSS display: flex to position proportional widths?如何使用 CSS display: flex 定位比例宽度?
【发布时间】:2018-03-19 08:52:10
【问题描述】:

我正在使用 flex 来定位两个 div:

我在这个容器中有两个 div,如果可能的话,我想像这样分隔它们:

xxxxxxxxxxx     xxxxxxxxxxx
x         x     x         x
x   45%   x 10% x  45%    x
x         x     x         x
xxxxxxxxxxx     xxxxxxxxxxx

如果没有足够的空间,然后让它们看起来像这样:

xxxxxxxxxxx 
x         x  
x         x 
x         x 
xxxxxxxxxxx 

xxxxxxxxxxx 
x         x  
x         x 
x         x 
xxxxxxxxxxx 

我试图这样做,但它似乎不起作用。

#city {
    margin-top: 2rem;
    border: 1px solid #ddd;
    display: -webkit-flex;
    display: flex;
    -webkit-flex-direction: row;
    flex-direction: row;
    -webkit-justify-content: flex-start;
    justify-content: flex-start;
    -webkit-align-items: center;
    align-items: center;
    padding: 8px 15px;
    margin-bottom: 20px;
    background-color: #f5f5f5;
    border-radius: 0.4rem;
}

<div id="city">
   <div style="flex-grow: 45;">xx</div>
   <div style="flex-grow: 10;"></div>
   <div style="flex-grow: 45;">yy</div>
</div>

谁能指出我可能做错了什么?

【问题讨论】:

  • 我会这样做:codepen.io/anon/pen/Eabovz,只使用基础弹性显示。
  • 您的建议似乎对我有用。我将把这个问题留一段时间,看看是否有其他可能的解决方案。感谢您抽出宝贵时间提出您的建议。
  • 关于您的问题似乎有一个令人困惑的信息:如果您以 % 为单位设置弹性项目的大小,则无论容器大小如何,它们都会始终具有该大小,除非它们还定义了 min-width 将发生包装的位置. 而且当它们换行时,您还忘记提供有关项目之间空间的信息?是不是也有点10%?如果是这种情况,您是否考虑过媒体查询,那么当空间足够时您将在哪里定义 flex-direction: row 当空间太窄时定义 flex-direction: column

标签: css flexbox


【解决方案1】:

除了 GCyrillus 的评论,我还建议使用支持其他旧浏览器的语法,即:

  display: -webkit-box;      /* OLD - iOS 6-, Safari 3.1-6 */
  display: -moz-box;         /* OLD - Firefox 19- (buggy but mostly works) */
  display: -ms-flexbox;      /* TWEENER - IE 10 */
  display: -webkit-flex;     /* NEW - Chrome */
  display: flex;             /* NEW, Spec - Opera 12.1, Firefox 20+ */

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多