Home > Web Front-end > CSS Tutorial > How to center in CSS Grid?

How to center in CSS Grid?

王林
Release: 2023-08-22 23:13:01
forward
1398 people have browsed it

A grid arranges content in a row and column layout. The same goes for CSS grids.

Using Flex for centering in CSS Grid

Set grid items as flexible containers−

display: flex
Copy after login

To center vertically and horizontally, use −

align-items: center;
justify-content: center;
Copy after login

Example

Let’s look at a complete example −

<!DOCTYPE html>
<html>
<head>
   <title>Grid and Flex Example</title>
   <style>
      html,body {
         margin: 0;
         padding: 0;
      }

      .box {
         display: grid;
         grid-template-columns: 1fr 1fr;
         grid-template-rows: 100vh;
      }

      .first,
      .second {
         display: flex;
         align-items: center;
         justify-content: center;
      }

      .first {
         background-color: orange;
      }

      .second {
         background-color: yellow;
      }
   </style>
</head>
<body>
   <div class="box">
      <div class="first">Left</div>
      <div class="second">Right</div>
   </div>
</body>
</html>
Copy after login

Output

如何在CSS Grid中居中?

Use CSS Grid to achieve centering without using Flex

We can also center without using Flex. We set the grid container to display: grid. When the display attribute is set to grid, the HTML element becomes a grid container -

grid-container {
   display: grid;
   grid-template-columns: 1fr 1fr;
   grid-auto-rows: 150px;
   grid-gap: 20px;
}
Copy after login

Grid items use relative positioning settings -

grid-item {
   position: relative;
   text-align: center;
}
Copy after login

Example

However,

<!DOCTYPE html>
<html>
<head>
   <title>Grid</title>
   <style>
      grid-container {
         display: grid;
         grid-template-columns: 1fr 1fr;
         grid-auto-rows: 150px;
         grid-gap: 20px;
      }

      grid-item {
         position: relative;
         text-align: center;
      }

      grid-container {
         background-color: red;
         padding: 10px;
      }

      grid-item {
         background-color: orange;
      }
   </style>
</head>
<body>
   <grid-container>
      <grid-item>This is in the center</grid-item>
      <grid-item>This is in the center</grid-item>
   </grid-container>
</body>
</html>
Copy after login

Output

如何在CSS Grid中居中?

The above is the detailed content of How to center in CSS Grid?. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template