【问题标题】:How to expand to maxWidth with alignSelf set如何使用 alignSelf 设置扩展到 maxWidth
【发布时间】:2022-01-09 07:34:21
【问题描述】:

以下代码正确扩展了 div 的 max-width

<div style="display: flex; flex-direction: column;">
    <div style="max-width: 500px;">
        <div style="background-color: red; height: 20px;"></div>
    </div>
</div>

结果:

但是,当我设置任何对齐方式时,最父 div 上的align-itemsmax-width div 上的align-self 等,将不再使用maxWidth,而是设置实际宽度到 0.
例如:

<div style="display: flex; flex-direction: column;">
    <div style="max-width: 500px; align-self: center">
        <div style="background-color: red; height: 20px;"></div>
    </div>
</div>

产生一个空白屏幕:

如何对齐 div(例如居中)并保持其宽度不变?目标不是诉诸使用width,因为这不会适应父宽度(可能是任何东西)。任何可以保持宽度但即使没有空间也不会坚持使用的解决方案,例如width,都可以。

【问题讨论】:

  • 如果width 超过max-width,则使用后者。因此,我们为什么不应该使用width

标签: javascript html css layout alignment


【解决方案1】:

使用align-self:centerflex-direction:column,您需要设置内部容器宽度,我将其设置为 100%,现在显示。

<div style="display: flex; flex-direction: column;background-color:grey">
  <div style="max-width: 500px; align-self: center; width:100%;background:black;">
    <div style="background-color: red; height: 20px;"></div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 2019-07-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-06
    • 2015-07-31
    • 1970-01-01
    • 2023-02-10
    • 2015-01-28
    相关资源
    最近更新 更多