【问题标题】:Let the highest element control the flex wrapper height让最高元素控制 flex wrapper 高度
【发布时间】: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`;
}

Codepen

【问题讨论】:

  • Flexbox 和 CSS-Grid 都需要您使用 rows,然后可以将其高度均衡到最高。事实上 JS 可能是这里最简单的选择。

标签: javascript css layout flexbox


【解决方案1】:

更改一些 CSS

nav {
  margin: 0 auto;
  width: 80%;
  display: flex;
  flex-direction: row;
  background: red;
}

https://codepen.io/anon/pen/RemZmb

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 1970-01-01
    • 2014-09-14
    • 2018-02-17
    • 1970-01-01
    相关资源
    最近更新 更多