2017-02-28 112 views
2

为什么在本示例中,.main元素(蓝色)仅用.aside-1(黄色)和.aside-2(粉红色)划分空间,而不是用所有元素划分空间?了解flex属性

enter image description here

我们有一个将占据一行的所有元素的包装。

.main我们说flex: 3 0px,我认为这个元素会比其他四个元素大3倍,占用3 /(3 + 1 + 1 + 1 + 1)。

但是,我注意到,用nowrap包装最小的项目是.main

而且与wrap,它分为两个最接近的元素。

看不懂这个。

.wrapper { 
 
    display: flex; 
 
    flex-flow: row wrap; 
 
    font-weight: bold; 
 
    text-align: center; 
 
} 
 

 
.wrapper>* { 
 
    padding: 10px; 
 
    flex: 1 100%; 
 
} 
 

 
.header { 
 
    background: tomato; 
 
} 
 

 
.footer { 
 
    background: lightgreen; 
 
} 
 

 
.main { 
 
    text-align: left; 
 
    background: deepskyblue; 
 
    height: 50vh; 
 
    flex: 3 0px; 
 
} 
 

 
.aside-1 { 
 
    background: gold; 
 
} 
 

 
.aside-2 { 
 
    background: hotpink; 
 
} 
 

 
.aside { 
 
    flex: 1 auto; 
 
} 
 

 
.aside-1 { 
 
    order: 1; 
 
} 
 

 
.main { 
 
    order: 2; 
 
} 
 

 
.aside-2 { 
 
    order: 3; 
 
} 
 

 
.footer { 
 
    order: 4; 
 
}
<div class="wrapper"> 
 
    <header class="header">Header</header> 
 
    <article class="main"> 
 
    <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. 
 
     Mauris placerat eleifend leo.</p> 
 
    </article> 
 
    <aside class="aside aside-1">Aside 1</aside> 
 
    <aside class="aside aside-2">Aside 2</aside> 
 
    <footer class="footer">Footer</footer> 
 
</div>

回答

5

首先来看看这条规则在你的代码:

.wrapper > * { 
    padding: 10px; 
    flex: 1 100%; 
} 

的选择上述的目标是所有五个伸缩项目

  • header
  • article
  • aside
  • aside
  • footer

flex成分分解成这样:

  • flex-grow: 1
  • flex-shrink: 1(默认情况下)
  • flex-basis: 100%

您写道:

为什么,在这个例子中,是.main元素(蓝色)将空间只有.aside-1(黄色)和.aside-2(粉红色),和不是与所有元素?

这就是为什么:

  1. 容器设置为flex-flow: row wrap,这意味着柔性物品被允许换行。
  2. 如上所述,所有弹性项目设置为flex-basis: 100%(即width: 100%),这意味着每行只能有一个弹性项目,除外......
  3. flex-basis: 100%只被应用到headerfooter因为...
  4. 它是由其他规则后来在级联序列正在被超越:

    .main { flex: 3 0px; } 
    
    .aside { flex: 1 auto; } 
    

然而,我注意到用nowrap包装纸最小的物品是.main

是的,因为如上所述,它有flex-basis: 0flex-shrink: 1

.main我们说flex: 3 0px,我认为说,这个元素将是3倍比其他四种元素更大,将占用3 /(3 + 1 + 1 + 1 + 1)。

不太。 flex-grow: 3意味着该元素将消耗的可用空间量是flex-grow: 1的其他弹性项目的3倍。这并不一定意味着它将是3倍大小。更多细节在这里:flex-grow not sizing flex items as expected


它可能会出现特异性应该笼络级联,并且所有项目应该得到flex-basis: 100%

  • .wrap > * { flex-basis: 100%; } VS .main { flex: 3 0px; }
  • .wrap > * { flex-basis: 100%; } VS aside { flex: 1 auto; }

不包括universal selector (*) has zero specificity。所以在这种情况下,所有选择器都具有相同的特性和源顺序。

+1

非常感谢@Michael_B :-)理解! – EFO