html - 居中 flex 元素下的 flex 盒网格

标签 html css flexbox

我想要在 .container 的左侧有一个介绍部分,在右侧有一个侧边栏。

.intro 部分的左侧,我希望有四个像网格一样等距的 div。

我在获取“网格设置”时遇到问题。我认为部分问题是 parent 有一些影响 child 的 flexbox 属性。

要求:介绍部分应在 .left-side 居中,“网格”不应居中,框应占用尽可能多的空间以适应 2 在一行中,中间有边距。 .intro 应该是左侧宽度的 80%。

我不想对结构进行任何重大更改,这只是我的元素设置方式的一小部分示例。

.container{
  width: 80%;
  margin: 0 auto; 
  display: flex;
}
.left-side{
  flex:8;
  display: flex;
  justify-content:center;
  flex-wrap: wrap;
}
.side-bar{
  flex: 2;
  height: 100vh;
  background: powderblue;


}
.intro{
  flex:3;
  width:80%;
  height: 300px;
  background: skyblue;
}

.box{
  background: red;
  width: 45%;
  height: 100px;
  flex:4;
  border:1px solid orange;
}
<div class="container">
  <div class="left-side">
    <div class="intro">
      intro
    </div>
    <div class="recent">
      <div class="box">1</div>
      <div class="box">2</div>
      <div class="box">3</div>
      <div class="box">4</div>
    </div>
  </div>
  <div class="side-bar">
    sidebar
  </div>

enter image description here

最佳答案

flex 元素也可以是 flex 容器。这使您能够在更大的容器中嵌套多个容器,使用 flex-direction: rowcolumn

对于您的布局,您可以构建一个包含两个 flex 元素的列。第一项 (.intro) 的宽度为 80%,可以水平居中。第二个元素 (.recent) 可以是一个 flex 容器,其中四个元素排列在 2x2 网格中。

.container {
    width: 80%;
    margin: 0 auto;
    display: flex;
    justify-content: center;
    height: 100vh;
}
.left-side {
    flex: 4;
    display: flex;
    flex-direction: column;
}
.side-bar {
    flex: 1;
    background: powderblue;
}
.intro {
    flex: 3;
    height: 300px;
    width: 80%;
    margin: 0 auto;
    background: skyblue;
}
.recent {
    display: flex;
    flex-wrap: wrap;
    background-image: url("http://i.imgur.com/60PVLis.png");
    background-size: contain;
}
.box {
    margin: 5px;
    flex-basis: calc(50% - 10px);
    height: 100px;
    box-sizing: border-box;
    background: red;
}

body { margin: 0; }
<div class="container">
    <div class="left-side">
        <div class="intro">intro</div>
        <div class="recent">
            <div class="box">1</div>
            <div class="box">2</div>
            <div class="box">3</div>
            <div class="box">4</div>
        </div>
    </div>
    <div class="side-bar">
        sidebar
    </div>
</div>

关于html - 居中 flex 元素下的 flex 盒网格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38034990/

相关文章:

jquery - 绝对元素 jQuery 居中问题

html - 在 anchor 标记内创建 anchor 标记

CSS 截断不起作用

html - Flexbox wrap - 最后一行的不同对齐方式

javascript - 用php突出显示html表中的选定行

html - 如何在单个 <p> 中垂直对齐 2 种不同的字体大小

html - css:表格高度不配合

jquery - css 完全删除而不仅仅是可见性 :hidden

CSS - 响应式柔性布局

html - flex 盒配置