I’ve been trying to figure out how to center an element within a flex box to the center of the page but I’m not sure how or if it can be done in a non-janky way. I’ve tried using absolute/relative positioning to move the elements into place but they never line up completely. I’ve have thought about using a grid and have the flex box element span the center columns but this seemed too janky as the number and size of the grid cells may not always be the same as the element I want to center.
Below I have created an example to demonstrate my problem. I am looking to center the right-most element in the flex box to the center of the page so that the blue box is at the center of the page and the red one is still to the left of it.
.title {
text-align: center;
font-weight: bold;
font-size: 40;
}
.box {
display: flex;
margin: auto;
justify-content: center;
}
<html>
<div class="title">
Test Title
</div>
<div class="box">
<div style="background-color: red; padding: 1rem;">Left Item</div>
<div style="background-color: blue; padding: 1rem;">Right item</div>
</div>
</html>
Edit: I have created a mock up image what I want to achieve using the example I provided. Sorry if I wasn’t able to explain exactly want I wanted before.
2
Answers
You can set
flex-direction: column;
and then give a height and a width for them.Use
absolute positioning
on the first div of the flex container and make it stick to the left by usingleft
propety and settin its vlue to 0. Also, it’s really important that you set position torelative
on the element you want its children absolutly positioned to, otherwise they will be psositioned absolutly to thebody
.