【问题标题】:Why aspectraio is not working in flexbox children?为什么 aspectraio 在 flexbox children 中不起作用?
【发布时间】:2023-02-01 07:07:30
【问题描述】:

HTML 部分

<div class="container">
            <div class="card">hi</div>
 </div>

CSS 部分

.container{
    width: 500px;
    aspect-ratio: 1/1;
    margin: auto;
    
    display: flex;
    gap: 50px;
    flex-wrap: wrap;

    background: rgba(0, 1000, 0, 0.1);
    justify-content: center;
    
}

.card{
    aspect-ratio: 1/1;
    width: 50px;
    background: rgba(0, 1000, 0, 0.1);
}

使用上面的代码,我希望 card 应该是 50px 的正方形。但令人惊讶的是它的高度变成了 500px。即与父母相同。

请解释为什么会这样。

如果我从 container 中删除 display: flex;,那么 card 将按预期变为完美的正方形。

【问题讨论】:

  • 您是否尝试过在容器中添加 align-items: start

标签: html css flexbox


【解决方案1】:

为什么会这样:align-contentalign-items的默认值是stretchalign-content: stretch 使 flex 行填充 flex 容器的横向尺寸(横向尺寸在您的示例中是高度,因为它是一个行 flexbox)。然后align-items: stretch 使.card 的横向尺寸填充线的横向尺寸,这只是被拉伸为容器的横向尺寸。

https://drafts.csswg.org/css-flexbox/#valdef-align-items-stretch。它说“如果弹性项目的交叉尺寸属性计算为自动[然后拉伸]。”

该条件的目的是使拉伸不会覆盖项目上指定的交叉尺寸(在您的示例中项目为 .card)。例如。如果有人将 height: 200px 放在 height:300px 行 flexbox 中的项目上,浏览器不应该用 300px 吹走那个 height: 200px

但是因为你的项目有height:auto,所以项目会拉伸。

flex 规范的这一部分是在 aspect-ratio 存在之前编写的。也许它应该扩展项目未拉伸的情况,以包括具有指定纵横比和明确主尺寸的项目,就像您的示例一样,但是......它没有。这就是我们得到的:(

所以,如果你不想让你的宽高比项目拉伸,你可以做以下任何事情:

  • 在项目上指定height
  • align-content: center(或startend)放在容器上
  • align-items: center(或startend)放在容器上
  • align-self: center(或startend)放在物品

【讨论】:

    【解决方案2】:

    指定高度将解决您的代码问题,并允许 display flex 仍然决定卡片在容器内的位置。看看这段代码。

    .container{
        width: 500px;
        aspect-ratio: 1/1;
        margin: auto;
        
        display: flex;
        gap: 50px;
        flex-wrap: wrap;
    
        background: rgba(0, 1000, 0, 0.1);
        justify-content: center;
        
        align-items: center; /*To center the card vertically inside of the container*/
    }
    
    .card{
        height: 50px;
        width: 50px;
        background: rgba(0, 1000, 0, 0.1);
      
        /*To center the text inside of the .card*/
        display: flex;
        justify-content: center;
        align-items: center;
    }
    <div class="container">
                <div class="card">hi</div>
     </div>

    【讨论】:

    • 当你在 flex 项目上使用 aspect-ratio 属性时,它可能不会像预期的那样工作,因为 flexbox 使用 flex 属性来控制 flex 项目的大小和位置,而不是 width 和 height 属性
    猜你喜欢
    • 2016-01-05
    • 2016-06-29
    • 2016-09-04
    • 2021-04-22
    • 2016-11-09
    • 1970-01-01
    • 2014-07-01
    • 2019-06-19
    • 1970-01-01
    相关资源
    最近更新 更多