Centering a box within a container

James

A Verified Legend
Gold Member
Local time
21:47
Joined
Oct 13, 2019
Messages
49

Hi folks,

I'm looking for help centering a box directly in the middle of an existing container.


I'm struggling to get it central vertically. (The grey box unit)

Cheers

 
Last edited:
Solution

Flexbox does the trick nicely here! Try this code...

ad.html:
<div class="container">
  <div>
    <div class="text">TITLE</div>
    <img src="https://via.placeholder.com/300x250">
  </div>
</div>
[CODE lang="css"...

Adam

Mr. Webwide
Administrator
Local time
21:47
Joined
Sep 24, 2019
Messages
1,243
Pronouns
he/him

Flexbox does the trick nicely here! Try this code...

ad.html:
<div class="container">
  <div>
    <div class="text">TITLE</div>
    <img src="https://via.placeholder.com/300x250">
  </div>
</div>
ad.css:
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background-color: #f1f1f1;
  padding: 5px;
  min-height: 400px;
}

.text {
  color: #CCCCCC;
  font-weight: 600;
  font-size: 11px;
  font-family: Open Sans;
}

 
Solution

Adam

Mr. Webwide
Administrator
Local time
21:47
Joined
Sep 24, 2019
Messages
1,243
Pronouns
he/him

If it worked, you can be the first to mark a question post as complete by clicking the tick icon next to the solution. 😄

 

Gummibeer

Astroneer
Moderator
Local time
22:47
Joined
Oct 5, 2019
Messages
1,150
Pronouns
he/him

Flexbox does the trick nicely here! Try this code...
ad.html:
<div class="container">
  <div>
    <div class="text">TITLE</div>
    <img src="https://via.placeholder.com/300x250">
  </div>
</div>
ad.css:
.container {
  display: flex;
  align-items: center;
  justify-content: center;
  text-align: center;
  background-color: #f1f1f1;
  padding: 5px;
  min-height: 400px;
}

.text {
  color: #CCCCCC;
  font-weight: 600;
  font-size: 11px;
  font-family: Open Sans;
}
Best usecase of flexbox! 🎉🚀

Before it was a relative container with an absolute child which is top&left 50% and -50% transform x&y. 😅🤯

 

Adam

Mr. Webwide
Administrator
Local time
21:47
Joined
Sep 24, 2019
Messages
1,243
Pronouns
he/him

Best usecase of flexbox! 🎉🚀

Before it was a relative container with an absolute child which is top&left 50% and -50% transform x&y. 😅🤯

Flexbox is without a doubt my favourite CSS addition since I started writing CSS! Yes, absolute positioning was hell. That or table-cell with vertical-align. :facepalm:

 

Gummibeer

Astroneer
Moderator
Local time
22:47
Joined
Oct 5, 2019
Messages
1,150
Pronouns
he/him

frustrated over it GIF by NETFLIX

 
Top