Solution 1 :

Wrap the boxes in a different container, and give that container display: flex;. Aso give .container3 a property flex-direction: column;

.container3 {
  border: 1px solid black;
  background-color: blue;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;
  padding: 10px;
  margin: 10px;
}

.box {
  height: 100px;
  width: 50px;
  border: 1px solid black;
  background-color: white;
  padding: 10px;
  margin: 10px;
}

.box-container {
  display: flex;
}
<div class="container3">
  <p>This is a container with 3 boxes</p>

  <div class="box-container">
    <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>

Codepen: https://codepen.io/manaskhandelwal1/pen/ZEpqYpL

Solution 2 :

Wrap the text in a div so that you can be able to style it separately. Like so:

.container3{
border: 1px solid black;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
margin: 10px;
height: 200px;
}

.box{
height: 100px;
width: 50px;
border: 1px solid black;
background-color: white;
padding: 10px;
margin: 10px;
}

.text1{
position: absolute;
margin-top: -150px;
}

And for the body:

<div class="container3">
 <div class="text1">
  <p>This is a container with 3 boxes</p>
 </div>
<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>

Problem :

I’m trying to position some text within a div that has other nested divs positioned within it.

Boxes and Text within a Div container

I’m trying to position the text (for this example) ‘this container has 3 boxes’ above the 3 div boxes (Box 1, 2 and 3) and aligned to the center.

<div class="container3">
<p>This is a container with 3 boxes</p>

<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>

Then my CSS is:

.container3{
border: 1px solid black;
background-color: blue;
display: flex;
justify-content: center;
align-items: center;
padding: 10px;
margin: 10px;
}

.box{
height: 100px;
width: 50px;
border: 1px solid black;
background-color: white;
padding: 10px;
margin: 10px;
}

I’ve used a simple example for the sake of just trying to position the text above the boxes in the parent div.

Should I also be placing the p in a div and giving it a class?

Any idea?

Thanks.

Comments

Comment posted by rjswainston

Thanks for this. Ran this version and also got the desire outcome.

Comment posted by Manas Khandelwal

You’re welcome ✌…

Comment posted by rjswainston

Great thanks – got this version to work!

By