Introduction
In this lab, we will be learning how to use CSS transforms to center child elements both vertically and horizontally within their parent element. We will achieve this by using relative and absolute positioning, along with the transform property and its translate function. This lab will equip you with a useful technique for positioning content on your web pages.
Transform Centering
index.html and style.css have already been provided in the VM.
To vertically and horizontally center a child element within its parent using CSS transforms, follow these steps:
- Set the
positionproperty of the parent element torelativeand that of the child element toabsoluteto position it relative to its parent. - Use
left: 50%andtop: 50%to offset the child element 50% from the left and top edge of the parent element. - Use
transform: translate(-50%, -50%)to negate its position, so that it is both vertically and horizontally centered. - Note that the fixed
heightandwidthof the parent element are for demonstration purposes only.
Here is an example HTML code:
<div class="parent">
<div class="child">Centered content</div>
</div>
And here is the corresponding CSS code:
.parent {
border: 1px solid #9c27b0;
height: 250px;
position: relative;
width: 250px;
}
.child {
left: 50%;
position: absolute;
top: 50%;
transform: translate(-50%, -50%);
text-align: center;
}
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 Transform Centering lab. You can practice more labs in LabEx to improve your skills.