Embarking on my HTML/CSS journey, I am taking on the challenge of creating my very first website. Currently tackling the final CSS project for Codecademy.
I've been tinkering with this task for what feels like an eternity and just can't seem to crack it. My goal is to center all the elements within the .mainContainer
. It seems logical that the 'Title' should be in the same container as the boxes, but I'm struggling to position it above the boxes while keeping everything centered both horizontally and vertically.
Below is the closest I have come to achieving this. The alignment at the bottom of the boxes looks centered, however, I require all content to be perfectly centered. What puzzles me is why I have used inline-block
for .mainContainer, but employed flex
for .boxContainer. Removing one property disrupts the centering effect. I never thought multiple display styles could be combined like this...what's the secret behind this?
https://jsfiddle.net/ichristian/ce9mou4w/2/
HTML
<div class='mainContainer'>
<h2>Title</h2>
<div class='boxContainer'>
<div class='box'>
<p>Box 1</p>
</div>
<div class='box'>
<p>Box 2</p>
</div>
<div class='box'>
<p>Box 3</p>
</div>
</div>
</div>
CSS
.mainContainer{
background-color: orange;
height: 200px;
width: 400px;
align-items: center;
text-align: center;
display: inline-block;
}
.boxContainer {
display: flex;
align-content: center;
justify-content: center;
align-items: center;
}
.box {
background-color: black;
color: white;
height: 40px;
width: 40px;
}
.box + .box {
margin-left: 40px;
}
EDIT: Not satisfied with the solution provided by the recommended question. The alternative answer I found below is much more straightforward.