首页 > 解决方案 > flex-wrap 不起作用的原因是什么?

问题描述

我查看了该网站上的其他问题,但没有一个与我的问题相似,应用 flex-direction:row; 没有帮助,应用各种宽度(最小宽度,最大宽度)也没有帮助。我是否使用错误的单位来设计容器中的物品?

我的目标是让内容换行。HTML 和 CSS:

body {
    margin: 0;
    padding: 0;
    background-color: #eeeeee;
}
h1, h5 {
    padding: 10px;
    margin: 0;
}

.pre-header {
    text-align: center;
}

#header-content1-1 {
    font-size: 1.15em;
    margin: 0;
    padding: 0;
}

hr {    
    margin-top: 20px;
    margin-bottom: 3px;
}

.container {
    display: flex;
    background-color: cornflowerblue;
    justify-content:space-between;
    max-width: 80%;
    margin: auto;
    align-items: center;
    height: 40vh;
    flex-wrap: wrap;
    

}

.flex-item {
    background-color: red;
    line-height: 9vh;
    width: 13%;
    text-align:center;
    flex-shrink: 3;

}
  <!DOCTYPE html>
  <html lang="en">
  <head>
      <meta charset="UTF-8">
      <meta http-equiv="X-UA-Compatible" content="IE=edge">
      <meta name="viewport" content="width=device-width, initial-scale=1.0">
      <meta name="description" content="Find out who was Avicii!">
      <link rel="stylesheet" href="style.css">
      <title>David</title>
  </head>
  <body>
    <header>
    <div class="pre-header">
        <h1 id="header-content1">Avicii - Tim Bergling</h1>
        <h5 id="header-content1-1">Swedish DJ, remixer, record producer, musician, and songwriter</h5>
    </div>
    </header>
<main>
<hr>
<div class="container">
    <div class="flex-item">E</div>
    <div class="flex-item">R</div>
    <div class="flex-item">I</div>
    <div class="flex-item">N</div>
    <div class="flex-item">N</div>
    <div class="flex-item">N</div>
    <div class="flex-item">N</div>
</div>
</main>

<footer>

</footer>
</body>
</html>

标签: css

解决方案


评论中提到的一种建议方法是具有适当的宽度(在您的情况下为 22%),因此它总计 100% 一些项目显示在下一行中。也可以添加边距(如margin: 0% 5%)以增加宽度。

有一种方法可以手动执行此操作,但您必须在 HTML 代码中添加类似于中断的内容。这是一个受此启发的解决方案。

<div class="container">
    <div class="flex-item">E</div>
    <div class="flex-item">R</div>
    <div class="flex-item">I</div>
    <div class="flex-item">N</div>
    <div class="flex-item">N</div>
  <div class="flex-item break"></div>
    <div class="flex-item f2">N</div>
    <div class="flex-item f2">N</div>
</div>

.break {
  flex-basis: 100%;
  height: 0;
}

这使用flex-basis。看看这个codepen的演示。

还可以选择在容器 div 中添加多一层 div,作为 flex-item 的父级。但总的来说,我建议使用动态宽度而不是使用这些方法,因为它们只会在您的盒子数量是动态的并且可能还需要一些 Js 时增加复杂性。


推荐阅读