Centering text using Grid
CSS grid is another popular layout tool that enables you to create complex and flexible grid-based layouts.
- Set the parent container to display: grid. (This enables the use of a CSS grid and turns the parent container into a grid container.)
- Use the place-items: center property (to center the child element both horizontally and vertically within the grid cell. This property is a shorthand for both justify-items and align-items.)
Example: This example shows how to center text inside a div using the grid 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;
display: grid;
place-items: center;
border: 2px solid black;
}
h1 {
color: green;
}
</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