假设这是我的 HTML,这意味着我有未知数量的 div 元素:
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
我想使用 Flexbox 以每行仅包含 3 个元素的方式排列元素。
这是我编写的可以实现的 CSS 代码:
html, body {
width: 100%;
height: 100%;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}
div {
width: 30%;
height: 20%;
border: solid;
}
使用百分比来定义大小有时可能很麻烦。我想问一下在这种情况下是否有一种方法可以在不使用百分比的情况下编写 CSS 代码。
当我width:100%
从html
and 中删除时body
,我得到一些奇怪的东西:
html, body {
/*width: 100%;*/
height: 100%;
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}
div {
width: 30%;
height: 20%;
border: solid;
}
<html>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
</html>
我想问一下在这种情况下是否有一种方法可以在不使用百分比的情况下编写 CSS 代码。
Yes, as being said, there is more than percent, like em
, rem
, vw
/vh
, that can be used, though I personally find %
to be one of the better, as it help you to scale your site very well.
Using percents to define size may sometimes be cumbersome. For example, I deleted
width: 100%
fromhtml, body
rule and I got something very ugly.
Yes, though that is expected behavior, as the body
does not behave as a standard block element in HTML5 and set as display: flex;
, Is body element a block level or inline element, which the html
elements does.
因此,当我们知道这一点时,我们可以flexbox
正确地利用的属性,通过做这样的事情,我们将html
元素作为第一个 flex 容器、body
它的 flex 项目以及第二个 flex 容器,用于div
元素。
此外,为了解决使用百分比的问题,所有祖先都需要一个高度,我使用了 viewport units vh
。
html {
display: flex;
}
body {
flex: 1; /* expand and take all available space */
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}
div {
width: 30%;
height: 20vh; /* 20vh equals 20% of the viewport */
border: solid;
}
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</body>
不过,我建议使用div
, 而不是body
, 作为容器
.container {
display: flex;
flex-wrap: wrap;
align-content: flex-start;
}
.container div {
width: 30%;
height: 20vh; /* 20vh equals 20% of the viewport */
border: solid;
}
<div class="container">
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句