Display Table Centering

Beginner

This tutorial is from open-source community. Access the source code

Introduction

In this lab, we will learn how to center a child element within its parent element using display: table. By using this technique, we can easily achieve both vertical and horizontal centering without having to resort to complex positioning or JavaScript. This is a useful skill to have when designing responsive layouts for websites and applications.

This is a Guided Lab, which provides step-by-step instructions to help you learn and practice. Follow the instructions carefully to complete each step and gain hands-on experience. Historical data shows that this is a beginner level lab with a 100% completion rate. It has received a 100% positive review rate from learners.

Display Table Centering

index.html and style.css have already been provided in the VM.

To center a child element both vertically and horizontally within its parent element, follow these steps:

  1. Add a container element with a fixed height and width.
<div class="container"></div>
  1. Add the child element inside the container element and give it a class of .center.
  <div class="center"><span>Centered content</span></div>
</div>
  1. In the CSS, apply the following styles to the container element:
  • Set height and width to the desired fixed values.
  • Add a border (optional).
.container {
  border: 1px solid #9c27b0;
  height: 250px;
  width: 250px;
}
  1. In the CSS, apply the following styles to the child element:
  • Use display: table to make the .center element behave like a <table> element.
  • Set height and width to 100% to make the element fill the available space within its parent element.
  • Use display: table-cell on the child element to make it behave like a <td> element.
  • Use text-align: center and vertical-align: middle on the child element to center it horizontally and vertically.
.center {
  display: table;
  height: 100%;
  width: 100%;
}

.center > span {
  display: table-cell;
  text-align: center;
  vertical-align: middle;
}

Please click on 'Go Live' in the bottom right corner to run the web service on port 8080. Then, you can refresh the Web 8080 Tab to preview the web page.

Summary

Congratulations! You have completed the Display Table Centering lab. You can practice more labs in LabEx to improve your skills.