jack blank jack blank - 5 months ago 19
CSS Question

flexbox grid under centered flex item

I would like an intro section on the left side of a

.container
and a side bar on the right.

On the left side underneath the
.intro
section I want there to be four divs equally spaced like a grid.

I'm having problems with getting the "grid set up". I think part of the problem is that the parent has some flexbox attribute effecting the children.

Requirement : The intro section should be centered in the
.left-side
and the "grid" should not be centered the boxes should take up as much space as necessary to fit 2 on a row with margins in between. The
.intro
should be 80 percent of the width of the leftside.

I don't want to do any major changes to the structure this is just a small sample of how my project is set up.



.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

Answer

Flex items can also be flex containers. This enables you to nest multiple containers, with flex-direction: row or column, in a larger container.

For your layout, you can build a column consisting of two flex items. The first item (.intro) has 80% width and can be centered horizontally. The second item (.recent) can be a flex container with four items arranged in a 2x2 grid.

.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;
}
.box {
    flex-basis: 50%;
    height: 100px;
    box-sizing: border-box;
    background: red;
    border: 5px solid white;
}
<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>

Comments