gpt4 book ai didi

html - flex-direction 列 flex 容器中 flex 元素的高度相同

转载 作者:行者123 更新时间:2023-12-03 16:41:06 29 4
gpt4 key购买 nike

有没有办法使用 flex-direction: column 在 flex 容器中放置 flex 项有相同的高度,只使用 CSS?

<div style="display: flex; flex-direction: column;">
<div class="flex-item">
<!-- other html elements with image, links, button etc. -->
</div>
<!-- ... -->
<div class="flex-item"></div>
</div>
JSFiddle: https://jsfiddle.net/hzxa9v54/

最佳答案

您将需要一个脚本来使用 Flexbox 解决该问题,此处使用 jQuery 完成。

Updated fiddle

堆栈片段

(function ($) {

// preload object array to gain performance
var $items = $('.item')

// run at resize
$( window ).resize(function() {
$.fn.setHeight(0);
});

$.fn.setHeight = function(height) {

// reset to auto or else we can't check height
$($items).css({ 'height': 'auto' });

// get highest value
$($items).each(function(i, obj) {
height = Math.max(height, $(obj).outerHeight())
});

// set the height
$($items).css({ 'height': height + 'px' });
}

// run at load
$.fn.setHeight(0);

}(jQuery));
.container {
display: flex;
flex-direction: column;
width: 200px;
}
.item {
border: 1px solid #ddd;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item">
come content 1
</div>
<div class="item">
come content 2
come content 3
</div>
<div class="item">
come content 4
come content 5
come content 6
</div>
<div class="item">
come content 7
</div>
</div>



根据评论更新,例如还需要考虑加载图像。

这是脚本的更新版本,可在图像加载后进行调整。

(function ($) {

// preload object array to gain performance
var $items = $('.item')

// run at resize
$( window ).resize(function() {
$.fn.setHeight(0);
});

$.fn.setHeight = function(height) {

// reset to auto or else we can't check height
$($items).css({ 'height': 'auto' });

// get highest value
$($items).each(function(i, obj) {
height = Math.max(height, $(obj).outerHeight())
});

// set the height
$($items).css({ 'height': height + 'px' });
}

function imageLoaded() {
$.fn.setHeight(0);
}

var images = $('.item img');
if (images) {
images.each(function() {
if( this.complete ) {
imageLoaded.call( this );
} else {
$(this).one('load', imageLoaded);
}
});
} else {
// run at load
$.fn.setHeight(0);
}

}(jQuery));
.container {
display: flex;
flex-direction: column;
width: 200px;
}
.item {
border: 1px solid #ddd;
margin: 10px 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item">
come content 1
</div>
<div class="item">
<img src="http://placehold.it/200x100/f00" alt="">
</div>
<div class="item">
come content 4
come content 5
come content 6
</div>
<div class="item">
come content 7
</div>
</div>

关于html - flex-direction 列 flex 容器中 flex 元素的高度相同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48304945/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com