【问题标题】:how to make flex container to shrink to a smallest reasonable size?如何使 flex 容器缩小到最小的合理尺寸?
【发布时间】:2021-11-26 02:43:54
【问题描述】:

我有一个按钮,它是带有两个项目的 flexcontainer。

.flex-container {
    display: flex
    column-gap: 1rem
    align-items: center
    margin-right: 10rem /* just for illustration sake */
    cursor: pointer

    &:hover
        opacity: 0.6
}

尽管项目不会拉伸,但它会连续占用所有可用空间。问题是当用户从按钮指向右侧时,它的反应就像鼠标在按钮上一样。我希望 flexbox 容器在第二个项目之后结束。它是怎么做到的?

margin-right: auto 不起作用

【问题讨论】:

    标签: css flexbox margin


    【解决方案1】:

    尝试使用display: inline-flex,这将使它成为一个像行内元素一样呈现的弹性容器。

    更新: - 我添加了两种类型的 flex 显示结果的演示。需要意识到的重要一点是 flex 行为是在 flex-container 的子级上进行的,两种类型的 flex 之间的布局没有区别。

    不同之处在于父容器相对于周围页面内容的呈现方式。使用display: flex - 容器被呈现为具有伸缩子元素的块级元素。使用display: inline-flex - 容器被呈现为具有伸缩子元素的内联级别元素。

    .flex-container {
        display: flex;
        align-items: center;
        border :solid 1px red; /* just for illustration sake */
        cursor: pointer;
        padding: 0 8px;
        }
        
    
    .inline-flex-container {
        display: inline-flex;
        align-items: center;
        border:solid 1px blue; /* just for illustration sake */
        cursor: pointer;
         padding: 0 8px;
        
        
        }
        
        
    .caret {
      width: 0;
      height: 0;
      border-style: solid;
      border-width: 5px 5px 0 5px;
      border-color: #000000 transparent transparent transparent;
      display: inline-block;
      margin-left: 6px;
      top: 0;
      position: relative;
    }
    <p>Display: flex (causes a block-level parent container and flexed children)</p>
    <div class="flex-container">
      <button type="button">Button</button>
      <span class="caret"></span>
    </div>
    
    <hr/>
    <p>Display: inline-flex (causes an inline-level parent container and flexed children</p>
    <div class="inline-flex-container">
      <button type="button">Button</button>
      <span class="caret"></span>
    </div>

    【讨论】:

    • 谢谢!我接受了你的回答,但我想弄清楚,“inline-flex”(来自查看器 PoV)的结果在哪些情况下与“width: max-content”不同?
    • 你也知道为什么“display:inline flex”可以和“display:inline-flex”不同的原因吗? MDN 说它们是相同的,第二个是遗留值。 developer.mozilla.org/en-US/docs/Web/CSS/display 但是 Chrome 94.0。出于某种原因不理解“display: inline flex”。
    • 没有连字符就相当于 display: inline;我会想到,这是无效的样式。很高兴我的解决方案奏效了——愉快的编码?
    • Without the hyphen it would be the equivalent of display: inline; 为什么然后 mdn 声明相反?他们恢复了 CSS 标准?
    • 是的,但我的浏览器似乎与您的答案比与文档更一致:)
    【解决方案2】:

    你可以在弹性容器上使用width: max-content。这将使容器的宽度与其内容相匹配。

    这类似于 gavgrif 的答案,但这不会建立内联格式上下文。这对您的用例可能很重要,也可能无关紧要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-11-16
      • 2018-07-20
      • 1970-01-01
      • 2012-11-23
      相关资源
      最近更新 更多