浮动块崩溃

Floating block collapse

我制作了网格系统,我遇到了 "strage" 块的行为 例如

HTML:

<div class="l_row">
    <div class="l_cell"></div>
    <div class="l_cell"></div>
    <div class="l_cell"></div>
    <div class="l_cell"></div>
</div>

CSS:

.l_row {
    min-width: 0px;
    width: 100%;
    max-width: 100%;
    margin: 2rem auto;
}
.l_row:before, .l_row:after {
    content: " ";
    display: table;
}
.l_row:after {
    clear: both;
}
.l_cell {
    float: left;
    padding-right: 15px;
    width: 25%;
}
.l_row .l_cell:last-child {
    padding-right: 0px;
}

如果 .l_cell 有一些内容至少有一个符号 1, a, &nbsp; - 效果很好,但如果 .l_cell 是空的,它会折叠成 width:0 并忽略 widthcss

在其中使用 &nbsp 来实现您想要的。

例如,

<div class="l_cell">&nbsp;</div>

这将 div 视为包含内容的块。

希望对您有所帮助。

找到... https://css-tricks.com/make-sure-columns-dont-collapse-horizontally/

.col {
    border-top: 1px solid white;
    border-bottom: 1px solid white;
    padding-top: 1rem;
    padding-bottom: 1rem;
    min-height: 1px;
}

您的布局可以通过一些小的调整来修复。

(1) 如果向 .l_cell 添加填充,这将增加框的宽度,并且宽度为 25% 的四个 .l_cell 块将无法放在一行中。您可以通过使用 box-sizing: border-box 来解决此问题,这将强制 .l-cell 将超宽保持在 25%,同时还包括 20px 的右填充。

(2) "zero collapse width" 效果是由于浮动的性质。由于您没有指定高度或最小高度,任何没有内容的浮动都将具有零高度但具有 25% 的宽度。如果您的示例中有一系列浮点数,则浮点数的左边缘将尽可能向左定位,直到它们碰到前一个浮点数的右边缘。如果浮动高度为零,则它没有右边缘,看起来宽度为零。如果你添加一个 min-height 值,所有的浮动都会按照你的预期定位。

.l_row {
    min-width: 0px;
    width: 100%;
    max-width: 100%;
    margin: 2rem auto;
}
.l_row:before, .l_row:after {
    content: " ";
    display: table;
}
.l_row:after {
    clear: both;
}
.l_cell {
    box-sizing: border-box;
    float: left;
    padding-right: 20px;
    width: 25%;
    min-height: 20px;
}
.l_cell:nth-child(odd) {
    background-color: beige;   
}
.l_cell:nth-child(even) {
    background-color: lightblue;   
}
.l_row .l_cell:last-child {
    padding-right: 0px;
}
<div class="l_row">
    <div class="l_cell">x1</div>
    <div class="l_cell"></div>
    <div class="l_cell">x3</div>
    <div class="l_cell"></div>
</div>