【发布时间】:2019-04-03 08:45:48
【问题描述】:
我正在设计一个包含许多子菜单的页脚大型菜单。内容是动态的。我想让最大的子菜单跨越包装器的一整列,因此还要设置它的高度。
我想出了一个解决方案,我正在测量块的高度并将包装高度设置为最高块的高度。
虽然这可以正常工作 - 解决方案感觉有点幼稚,并且告诉我有更优雅的解决方案。最好没有javascript。你觉得怎么样?我尝试了 CSS 网格,但无法得到我想要的结果。
nav {
margin: 0 auto;
width: 80%;
display: flex;
flex-direction: column;
align-content: center;
flex-wrap: wrap;
}
包装元素的高度是用Javascript设置的
/*
Set the height of the wrapper to the highest blocks height
*/
function rearrangeBlocks() {
// Grab the whole menu
const section = document.querySelector('nav');
// Grab all the blocks
const allBlocks = document.querySelectorAll('.block');
// Grab the highest block
const longestBlock = Array.from(allBlocks).reduce((longest, current) => {
if (current.getBoundingClientRect().height > longest.getBoundingClientRect().height) {
return current;
} else {
return longest;
}
});
// Set the height of the menu to the same height of the highest menu item
section.style.height = `${longestBlock.offsetHeight}px`;
}
【问题讨论】:
-
Flexbox 和 CSS-Grid 都需要您使用 rows,然后可以将其高度均衡到最高。事实上 JS 可能是这里最简单的选择。
标签: javascript css layout flexbox