【问题标题】:why is flex-basis size not being applied?为什么没有应用基于弹性的尺寸?
【发布时间】:2017-03-21 00:07:14
【问题描述】:

我有一个输入元素,我想使用 flex shrink 来扩大和缩小它,但它的 flex-basis 大小没有被应用。

这是我的html:

<input type="text"/>

还有我的 CSS:

input{
  background-color: black;
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
  flex: 0 1 450px;
}

为什么没有应用基本尺寸?它被设置为比 450px 小得多的宽度。

Here 是一个例子。

【问题讨论】:

  • 因为它适用于一个弹性盒子的孩子:jsfiddle.net/614abhj2/2
  • flexflex-basisflex-growflex-shrink 是适用于 flex 项(flex 容器的子项)的属性。要调整 flex 容器的大小,您可以使用 widthheightmin-widthmax-widthmin-heightmax-height。更多细节在这里:stackoverflow.com/q/34352140/3597276

标签: html css flexbox


【解决方案1】:

/* Latest compiled and minified CSS included as External Resource*/

/* Optional theme */
@import url('//netdna.bootstrapcdn.com/bootstrap/3.0.0/css/bootstrap-theme.min.css');

body {
    margin: 10px;
    display:flex;
}

input{
  background-color: black;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
  flex: 0 1 450px;
}
&lt;input type="text"/&gt;

检查一下

【讨论】:

  • 有什么区别?
【解决方案2】:

您已将display: flex 应用于&lt;input&gt; 元素而不是div。

理想的方法是使用容器/包装器,然后制作容器display: flex,然后使用flex-basis-Here is your Fiddle updated控制输入

HTML

<div class="container">
   <input type="text"/>
</div>

CSS

.container{
  display: flex;
  align-items: center;
  justify-content: center;
  flex-direction: row;
  flex-wrap: wrap;
}

.container input { flex: 0 1 450px; }

【讨论】:

    【解决方案3】:

    你需要建立一个flex格式上下文

    这与建立块格式化上下文相同,除了 使用 flex 布局而不是块布局。

    要使flex-basisflex-growflex-shrink 等属性起作用,元素必须参与弹性格式化上下文。

    弹性项目为其内容建立一个新的格式化上下文。这 此格式化上下文的类型由其显示值确定,如 通常。然而,弹性项目本身是弹性级别的盒子,而不是 块级盒子:它们参与容器的弹性 格式化上下文,不在块格式化上下文中。

    var el = document.querySelector("input");
    console.log("input width: " + el.offsetWidth + "px");
    .flex-container {  /* Flex formatting context, this makes the element a flex container */
      display: flex;
    }
    input {  /* Direct children of flex containers are now flex items */
      background-color: black;
      flex: 0 1 450px;
      box-sizing: border-box;
    }
    <section class="flex-container">
      <input type="text" />
    </section>

    Revised jsFiddle


    来源:W3C CSS Flexible Box Layout Module Level 1

    【讨论】:

      【解决方案4】:

      将弹性属性应用到输入容器而不是输入。

      看看下面的sn-p:

      .input-holder {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: row;
        flex-wrap: wrap;
      }
      
      .input-holder input {
        flex: 0 1 450px;
        background: #000;
      }
      <div class="input-holder">
        <input type="text"/>
      </div>

      希望这会有所帮助!

      【讨论】:

        猜你喜欢
        • 2018-09-04
        • 2021-09-28
        • 2020-07-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-01-22
        • 1970-01-01
        相关资源
        最近更新 更多