我在理解Flexbox中不同的图像尺寸配置时遇到了一些困难。似乎每次尝试应用它们时,都会得到不同的结果。
有人会说一些不同情况下的连贯逻辑,而不是说“一切都取决于情况”吗?我想知道为什么每次结果都不一样。我不太在乎图像的比例,而更多地取决于视口大小的图像位置。假设我在所有情况下都使用object-fit:cover。这是一个将两个图像并排放置的示例。
index.html
<section>
<figure>
<img src="profile image1.jpg" alt="">
</figure>
<figure>
<img src="profile image2.jpg" alt="">
</figure>
</section>
style.css
section {
display: flex;
}
场景1
style.css
/* figure wrapper's dimension is set, but not those of the images */
figure {
flex: 50%;
width: 100%;
height: auto;
}
场景2
style.css
/* figure wrapper's dimension and the images' dimension are both set with a percentage unit */
figure {
flex: 50%;
width: 100%;
height: auto;
}
img {
width: 100%;
height: 100%;
}
场景3
style.css
/* figure wrapper's dimension and the images' dimension are both set with the pixel unit */
figure {
flex: 50%;
width: 400px;
height: 400px;
}
img {
width: 400px;
height: 400px;
}
方案4
style.css
/* figure's dimension is set with max-width and max-height */
figure {
flex: 50%;
max-width: 400px;
max-height: 400px;
}
img {
width: 100%;
height: 100%;
}
Senario 5
style.css
/* figure's dimension and image's dimension are set with max-width and max-height */
figure {
flex: 50%;
max-width: 400px;
max-height: 400px;
}
img {
max-width: 100%;
max-height: 100%;
}
我想我最终想弄清楚将图像放入具有不同像素/百分比尺寸单位配置的容器中有什么好处。
答案 0 :(得分:2)
未设置图像宽度(场景1),图像将使用其 原始宽度和高度,例如,如果您正在使用尺寸为1024 * 768的图像,则它将填充您的页面宽度的1024 px和页面高度的768px。此行为将忽略任何内容 您用于其包装器的配置,即图。
已将img宽度设置为100%,这意味着您已强制元素遵守其容器的宽度(在本例中为该图)。因此,在这种情况下,flex配置生效。
答案 1 :(得分:1)
flex: 50%
是flex-basis: 50%; flex-grow: 1; flex-shrink: 1
的简写。这些数字既有flex-basis
也有width
,这是没有用的。仅考虑弹性基础。因此,该算法将首先在其父级宽度的50%处创建图形,然后将其增长或均匀缩小以适合所述父级。如我之前所说,无论图像太大,图像都会溢出。width: 100%
是没有用的。height
和width
的图像会使它们拉伸以填充其父级。在这种情况下,我不知道确定其大小的确切算法,因为我从不这样做。在这种情况下,我建议仅设置width
,以便自动选择图像的高度以符合纵横比。400px
的宽度和高度被忽略,因为flex: 50%
设置了具有优先权的柔韧性基础。max-width
和max-height
均已设置,因此图像可能会在此过程中失去其原始纵横比。您根本不需要使数字增长。如果要样式化样式并将图例添加到图像,这可能是理想的。示例:
section {
display: flex;
}
figure {
background-color: #dca;
padding: 20px;
}
img {
max-width: 100%;
}
<!-- PS: the width and height attributes on img tags emulate actual image size -->
<section>
<figure>
<img width="200" height="100" alt="">
<legend>Fig. 1</legend>
</figure>
<figure>
<img width="400" height="100" alt="">
<legend>Fig. 2</legend>
</figure>
</section>
任何元素的默认弹性样式为:
flex-grow: 0; /* do not grow */
flex-shrink: 1; /* shrink automatically to fit parent */
flex-basis: auto; /* but otherwise determine size based on content */
然后再次,您可能希望元素整齐地放入列中,在这种情况下,flex: 50%
元素周围的包装上的figure
可能更好。无论如何,在进行测试时始终可以为元素添加背景色!