David Kris
David Kris

Reputation: 661

Centering Flex Boxes

I have code below for multiple flex boxes. How would I center them vertically in the page when the page is being expanded? I tried using justify-content: center; in my flex-container but it does work when I'm using flex: 1 0 auto; to make the boxes responsive. Anything helps, thanks.

.flex-container {
    display:flex;}

.flex-post { 
    background-color: #f1f1f1;
    margin: 10px;
    text-align: center;
    line-height: 75px;
    font-size: 30px;
    flex: 1 0 auto;
    height:auto;
    max-height:270px;
    max-width:270px;
    align-items: center;
    justify-content: center;
    display:flex;}

.flex-post:before {
    content:'';
    float:left;
    padding-top:100%;}

.flex-post:hover { 
    background-color: rgba(1,1,1,0.5);}
<div>
</div>

<div class="flex-container">
    <div class="flex-post">1</div>
    <div class="flex-post">2</div>
    <div class="flex-post">3</div>
</div>
<div class="flex-container">
    <div class="flex-post">4</div>
    <div class="flex-post">5</div>
    <div class="flex-post">6</div>
</div>
<div class="flex-container">
    <div class="flex-post">7</div>
    <div class="flex-post">8</div>
    <div class="flex-post">9</div>
</div>

Upvotes: 0

Views: 52

Answers (1)

Lansana Camara
Lansana Camara

Reputation: 9873

Try this out:

.full-width {
    width: 100%;
}

.full-height {
    height: 100%;
}

.flex {
    display: flex;
}

.flex-row {
    flex-direction: row;
}

.flex-column {
    flex-direction: column;
}

.flex-center {
    justify-content: center;
}

.flex-start {
    justify-content: flex-start;
}

.flex-end {
    justify-content: flex-end;
}

Now with those classes, you can do things like this:

Horizontally center:

<div class="flex flex-row flex-center">foo</div>

Vertically center:

<div class="flex flex-column flex-center full-height">foo</div>

Upvotes: 2

Related Questions