How to Centre an Element Vertically Using Table-Cell

Let's consider the following scenario where I need to position an element in the horizontal and vertical middle of a parent div.

To represent this situation we can use a simple blue square within a parent element with dashed line.

We need to end up with the following:

Centering elements using table-cell

THE HTML

<div class="dashedBox">
      <div class="blueSquare"></div>
</div>

 

THE CSS

First, we will style the outer dashedBox div as follows:

.dashedBox {
  display: table-cell;
  vertical-align: middle;
  border: 1px dashed #000;
  height: 200px;
  width: 400px;
}

Line 2: this is the important part of this code as it defines the type of display for the element
Line 3: this will now centre any content in this element

We shall now style the blueSquare:

.dashedBox {
  display: table-cell;
  vertical-align: middle;
  border: 1px dashed #000;
  height: 200px;
  width: 400px;
}

.blueSquare {
  margin: auto;
  background: blue;
  height: 30px;
  width: 30px;
}

Line 10: this will centre the blue square horizontally.

There are many other ways to centre content both horizontally and vertically but each usually comes with its own pros and cons.

It's up to you as the developer to select an option which will work for you and provide you with the best compatibility.

Want to Learn More?

Become a member and get access to the member only area of this site here.

Comments

Your email address will not be published.

PHP for Beginners

Enrol in the full course here

PHP, MySQL and PDO

Coming soon, a full course on using PHP, MySQL and PDO. Be notified as soon as the course goes live.