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.
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:
- Add a container element with a fixed
heightandwidth.
<div class="container"></div>
- Add the child element inside the container element and give it a class of
.center.
<div class="center"><span>Centered content</span></div>
</div>
- In the CSS, apply the following styles to the container element:
- Set
heightandwidthto the desired fixed values. - Add a border (optional).
.container {
border: 1px solid #9c27b0;
height: 250px;
width: 250px;
}
- In the CSS, apply the following styles to the child element:
- Use
display: tableto make the.centerelement behave like a<table>element. - Set
heightandwidthto100%to make the element fill the available space within its parent element. - Use
display: table-cellon the child element to make it behave like a<td>element. - Use
text-align: centerandvertical-align: middleon 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.