CSS Flexbox动态纵横比代码受内容影响

CSS Flexbox动态纵横比代码受内容影响,css,flexbox,Css,Flexbox,对于网页网格布局,我决定使用Flexbox。现在我想实现一些“自动功能”,以便以后可以插入网格框,而无需在HTML中添加类或样式。该功能之一是使长方体的高度始终等于其宽度的75%——即使长方体的大小通过例如browserwindow resize来调整。当然,如果盒子内容扩展了75%的高度,它应该(并且只有在那时)增加其高度以适应内容。我花了几个小时寻找一个合适的解决方案,但最终还是成功了。所以我想,至少,直到我把内容添加到盒子里 只要框为空,自动纵横比就可以正常工作。如果我添加内容,75%的宽

对于网页网格布局,我决定使用Flexbox。现在我想实现一些“自动功能”,以便以后可以插入网格框,而无需在HTML中添加类或样式。该功能之一是使长方体的高度始终等于其宽度的75%——即使长方体的大小通过例如browserwindow resize来调整。当然,如果盒子内容扩展了75%的高度,它应该(并且只有在那时)增加其高度以适应内容。我花了几个小时寻找一个合适的解决方案,但最终还是成功了。所以我想,至少,直到我把内容添加到盒子里

只要框为空,自动纵横比就可以正常工作。如果我添加内容,75%的宽度总是通过内容的扩展添加到它的高度。我做了一个JSFIDLE来清楚地想象问题:

,可视化以下代码:

HTML代码:

<div class="container">
    <div class="content-cell"></div>
    <div class="content-cell"></div>
</div>

<div class="container">
    <div class="content-cell">
        This cell has an inreased height because of
        it's content. The empty space below the
        content is the 75% of the cells width.
    </div>
    <div class="content-cell"></div>
</div>
.container {
    display: flex;
    width: 400px;
}

.content-cell {
    flex: 1 1 0;
    margin: 10px;

    background-color: #ccc;
}

.content-cell::after {
    content: "";

    display: block;
    padding-top: 75%;
}
<div class="mybox aspect-full">
    This is text, that would normally extend the box downwards.
    It is long, but not so long that it extends the intended aspect-ratio.
</div>
.mybox {
    width: 200px;
}

.aspect-full::before {
    content: '';

    display: block;
    padding-top: 100%;
    float: left;
}
如果我不太清楚的话,它看起来像是一个浮动问题-但是我认为
:before
/
:after
选择器应该在使用它的元素之前添加块元素,而不是在它内部


有人知道如何解决这个问题吗?

这似乎是互联网上一个非常普遍的问题,你找到的大多数解决方案要么是包装内容,要么是绝对定位内容,要么两者兼而有之。这有许多和具体情况有关的缺点。在花了几个小时研究代码之后,我终于找到了一个CSS比例组合,它可以在不需要添加任何DOM或使内容绝对定位的情况下工作。这看起来很简单,我想知道为什么我花了这么长时间,为什么你在网上找不到它

HTML:

<div class="container">
    <div class="content-cell"></div>
    <div class="content-cell"></div>
</div>

<div class="container">
    <div class="content-cell">
        This cell has an inreased height because of
        it's content. The empty space below the
        content is the 75% of the cells width.
    </div>
    <div class="content-cell"></div>
</div>
.container {
    display: flex;
    width: 400px;
}

.content-cell {
    flex: 1 1 0;
    margin: 10px;

    background-color: #ccc;
}

.content-cell::after {
    content: "";

    display: block;
    padding-top: 75%;
}
<div class="mybox aspect-full">
    This is text, that would normally extend the box downwards.
    It is long, but not so long that it extends the intended aspect-ratio.
</div>
.mybox {
    width: 200px;
}

.aspect-full::before {
    content: '';

    display: block;
    padding-top: 100%;
    float: left;
}
我能找到的唯一缺点是你手机的内容必须浮动。如果在一个子对象上使用
clear
,则该子对象位于扩展块下方,您将回到原始问题。如果需要清除这些纵横比单元中的div的浮动,可以考虑包装它们并保持包装器浮动。