使用弹性框分布带边框的填充图形,使图像高度相等



我正在使用jquery将包装器div的弹性增长值设置为图形图像的纵横比。 这是基于此处的建议。

但是当我在图形中添加边框和填充时,图像的高度不再相同。 有没有办法在此计算中包含边框和填充以使所有图像具有相同的高度?还是另一种让这些图形图像具有相同高度的方法?

如果您从图形 css 中注释掉边框和填充,则所有图形图像的高度都变得相等,这一点变得很明显。

编辑:我刚刚意识到这在Chrome中具有完全不同的行为。 在火狐中几乎没问题,但在Chrome中,图像大小完全不同!

$(document).ready(function() {
$('div.pack').css({
"display": "flex"
})
.children().each(function() {
$(this).css({
"width": "100%"
});
var $img = $(this).find('img');
var aspect = $img[0].naturalWidth / $img[0].naturalHeight;
$(this).wrap('<div style="display:flex; flex: 0% ' + aspect + ' 1;" />')
$img.css({
"width": "100%",
"height": "auto"
})
});
});
figure {
padding: 4px;
border: 1px solid lightgray;
margin: 0;
}
div.pack>div:not(:last-child) {
margin-right: 1%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pack'>
<figure>
<img src="http://via.placeholder.com/300x300">
<figcaption>Big cap tion Caption here Big cap tion Capt ion here </figcaption>
</figure>
<figure>
<img src="http://via.placeholder.com/300x500">
<figcaption>Caption here</figcaption>
</figure>
<figure>
<img src="http://via.placeholder.com/600x150">
<figcaption>Caption here</figcaption>
</figure>
</div>

这是因为您要向其添加另一个包装器。不要将数字包装在<div>s 中,它将按预期工作。

但它不适用于非常小的设备,因为字幕会太高,从包装开始。我建议您使用@media查询在手机上全宽显示它们。由于您要对style属性进行硬编码,因此需要!important才能应用@media查询flex

$(window).on('load', function() {
$('div.pack').children().each(function() {
let img = $(this).find('img')[0], 
asp = img.naturalWidth / img.naturalHeight;
$(this).css({
flex: asp + ''
})
});
});
figure {
padding: 4px;
border: 1px solid lightgray;
margin: 0;
font: italic normal 14px/normal serif;
}
div.pack>figure:not(:last-child) {
margin-right: 1%;
}
figure img {
width: 100%;
height: auto;
}
.pack {
display: flex;
}
@media (max-width: 560px) {
.pack {
flex-wrap: wrap;
}
.pack figure:not(#duh) {
flex: 1 0 auto !important;
max-width: calc(100% - 10px);
margin: 0 0 10px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='pack'>
<figure>
<img src="http://via.placeholder.com/300x300">
<figcaption>Big cap tion Caption here Big cap tion Capt ion here </figcaption>
</figure>
<figure>
<img src="http://via.placeholder.com/300x500">
<figcaption>Caption here</figcaption>
</figure>
<figure>
<img src="http://via.placeholder.com/600x150">
<figcaption>Caption here</figcaption>
</figure>
</div>


旁注:我真的不明白为什么flex: 0% x 1;被解析为:

flex-grow: 0%;
flex-shrink: x;
flex-basis: 1;

工作原理与flex: x;相同,后者被正确解析为:

flex-grow: x;
flex-shrink: 1;
flex-basis: 0%;

但我不希望它跨浏览器/跨设备工作,所以我只是将其恢复为原始形式。

我还将整个脚本从document.ready移动到window.load事件,因为您真的不希望它在加载<img>之前运行。


最后,在前端开发中使用Firefox(至少)有两个主要缺点:

  • 在过去的几年里,它的开发工具一直落后于Chrome
  • 几个月
  • 它的市场份额比Chrome小 - 这意味着您正在为不到15%的用户进行开发,稍后,在跨浏览器阶段,您可能需要为超过60%的用户应用修复程序。反过来做更有意义。

最新更新