Shinji-san Shinji-san - 4 months ago 32
HTML Question

Centering flexbox on page with absolute positioning

I am having a lot of trouble centering. So basically I want my container div in the dead center of the page. I tried having a wrapper div relative positioning and making my container div absolute positioning with top and left: 50 percent but now the whole right column(my third column) is missing, and my second column's text has flown outside of the container div. At this point it just seems like everything I'm doing is counter-intuitive to what I had expected..I tried taking off margin: auto but that just made the problem worse. In the picture my container div is near the bottom of the screen and I don't know why. But my ultimate goal is to center it dead center in the page and be able to put percentage height and width on it.



*{
margin: 0;

}

html, body{
height: 100%;
}


#bigwrap{
position: relative;
height: calc(100vh - 150px);
width: 100%;
}

.container {
display:flex;
position: absolute;
flex-wrap:wrap;
flex-direction:row;
justify-content:flex-start;
align-items:center;
width: 80%;
top: 50%;
left: 50%;
margin-left: 40%;
height: 70%;
}

.container img{
width: 50px;
height: 50px;
}

.left {
display: flex;
flex-flow: row wrap;
align-items: flex-start;
justify-content: center;
order:1;
background:red;
flex-basis:100%;
height:100%;
}


.left img{
max-width: 100%;
}


.middle {
display:flex;
flex-flow: row wrap;
align-content: flex-start;
justify-content: flex-start;
order:3;
background:green;
flex-basis: 100%;
height:100%;
}
.right {
order:2;
background:yellow;
flex-basis:100%;
height:100%;
}

.box{
display: flex;
flex-flow: row wrap;
align-items: flex-start;
justify-content: flex-start;
height: 200px;
width: 200px;
}




@media screen and (min-width:600px) {
.container {
flex-wrap:nowrap;
}

.left {
flex-basis:1;
order:1;
}
.middle {
flex-basis:1;
order:2;
}
.right {
flex-basis:1;
order:3;
}
}

<div id="bigwrap">
<div class="container">
<div class="left">
<img src="cat1.jpeg" alt="cat">
<img src="cat1.jpeg" alt="cat">

</div>
<div class="middle">
<div class="box">`
<p>texteiehiefief texteiehiefief texteiehiefief texteiehiefief </p>


</div>

<div class="box">`
<p>texteiehiefief texteiehiefief texteiehiefief texteiehiefief </p>


</div>

</div>

<div class="right">

</div>
</div>

</div>





enter image description here

Answer

You were almost there with top: 50% and left: 50%.

You need to also add a transform rule and remove the margin-left: 40%.

.container {
    display: flex;
    position: absolute;
    flex-wrap: wrap;
    flex-direction: row;
    justify-content: flex-start;
    align-items: center;
    width: 80%;
    top: 50%;
    left: 50%;
    transform: translate(-50%,-50%); /* NEW */
    /* margin-left: 40%;                REMOVE */
    height: 70%;
}

For an explanation of how the transform property helps to center an absolutely positioned element see: Element will not stay centered, especially when re-sizing screen