Centering text using Transform Property
- Set the parent container to position: relative. This enables the use of absolute positioning for the child element.
- Set the child element to position: absolute. This enables the use of absolute positioning for the child element.
- Set the child element’s top and left properties to 50%. This positions the child element at the center of the parent container.
- Use transform: translate(-50%, -50%) to center the child element both horizontally and vertically.
Example: This example shows how to center text inside a div using the transform property of CSS.
<!DOCTYPE html>
<html lang="en">
<head>
<title>
Center text horizontally and
vertically inside a div block
</title>
<style>
.container {
height: 300px;
width: 645px;
position: relative;
border: 2px solid black;
}
h1 {
position: absolute;
top: 50%;
color: green;
left: 50%;
transform: translate(-50%, -50%);
}
</style>
</head>
<body>
<div class="container">
<h1>GeekforGeeks</h1>
</div>
</body>
</html>
Output:
How to Center Text in a Div Vertically and Horizontally
Centering text within a <div>
block is essential for creating visually attractive layouts. Various methods, such as flexbox, grid, and CSS transforms, offer solutions with distinct benefits. In this article, we’ll explore various methods to center text both horizontally and vertically using CSS. From classic approaches to modern flexbox solutions,
Table of Content
- 1. Centering text using Flexbox
- 2. Centering text using Grid
- 3. Centering text using Text Align
- 4. Centering text using Table Cell
- 5. Centering text using Transform Property