【问题标题】:Flex positionning in CSSCSS 中的 Flex 定位
【发布时间】:2019-05-26 15:24:34
【问题描述】:

我正在创建一个 React Native 应用程序,我想使用 flex 来构造我的元素在屏幕上的定位。考虑到我们有以下屏幕:红色区域的 flex-grow 值为 1,黄色区域为 2,绿色区域为 3。它们都有一个父级,具有 display: flexflex-grow: 1。 (这是 React Native,所以默认的 flex-direction 是 column)。

我的问题如下:如果没有绿区怎么办?我怎么能告诉 flex 将父级的 1/6 用于红色区域,2/6 用于黄色区域,其余为空?

【问题讨论】:

  • 请粘贴您的 CSS 或制作一个 codepen 示例,这样会更好
  • Théo,你想只用 flex 做,还是你能听到其他建议?
  • @NicoDiz 认为 react-native 目前不支持 CSS 网格...
  • 因为你在 react-native 中没有 伪元素,所以你需要一个绿色部分的元素来使这段代码工作......
  • 我的解决方案可以使用github.com/GeekyAnts/react-native-easy-grid

标签: reactjs css react-native flexbox


【解决方案1】:

通过将flex-grow: 0flex-shrink: 0 应用于弹性项目,我能够实现您描述的布局。通过将 flex-basis 设置为适当的百分比,无论是否存在第三个 div,布局都可以保持。

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}
<div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
  <div class="three">THREE</div>
</div>

这次我省略了第三个 div,我们得到了相同的布局:

.wrapper {
  display: flex;
  flex-flow: column nowrap;
  height: 100vh;
}
.one {
  flex: 0 0 16.666%; /* dont grow, dont shrink, starting basis */
  background: red;
}
.two {
  flex: 0 0 33.333%; /* dont grow, dont shrink, starting basis */
  background: yellow;
}
.three {
  flex: 0 0 50%; /* dont grow, dont shrink, starting basis */
  background: green;
}
<div class="wrapper">
  <div class="one">ONE</div>
  <div class="two">TWO</div>
</div>

【讨论】:

    【解决方案2】:

    Théo,你想只用 flex 做,还是你能听到其他建议?

    这是使用grid 的完美示例。

    小提琴:https://jsfiddle.net/h17tezLd/

    <div class="container">
        <div class="zone1"></div>
        <div class="zone2"></div>
        <div class="zone3"></div>
    </div>
    
    <style>
        .container {
            width: 150px;
            height: 300px;
            background: grey;
            display: grid;
            grid-template: 1fr 2fr 3fr / 100%;
            }
        .zone1 { background: red; }
        .zone2 { background: blue; }
        .zone3 { background: green; }
    </style>
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-13
    • 1970-01-01
    • 1970-01-01
    • 2012-04-04
    • 1970-01-01
    相关资源
    最近更新 更多