Home > Back-end >  How to vertically center text within a grid row in css
How to vertically center text within a grid row in css

Time:03-16

[Here is the code for a minimally reproducible example of the problem I am having. I looked within all the other posts, and tried them, but they didnt work for some reason.]

When you load the example, the small text wont align with the big text, presumably because it is inside a row. Is there a way to make Small_Text vertically aligned with Big_Text?

<!DOCTYPE html>
<html>
    <head>
        <style>
            /* GRID AREA SYNTAX REFERENCE:
        grid-row-start, grid-column-start, grid-row-end, grid-column-end
        */
            body {
                display: grid;
                grid-template-columns: 1fr 1fr;
                grid-column-gap: 10px;
                /*Body Border Here for better visibility.*/
                border: 1px solid black;
            }
            .c1 {
                grid-area: 1 / 1 / 2 / 2;
                border: 1px solid black;
                text-align: center;
            }
            .c2 {
                grid-area: 1 / 2 / 2 / 3;
                border: 1px solid black;
                text-align: center;
            }
        </style>
    </head>
    <body>
        <h1 >Big_Text</h1>
        <p >Small_Text</p>
    </body>
</html>

CodePudding user response:

Use align-items:center

body {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-column-gap: 10px;
  /*Body Border Here for better visibility.*/
  border: 1px solid black;
  align-items: center;
}

.c1 {
  grid-area: 1 / 1 / 2 / 2;
  border: 1px solid black;
  text-align: center;
}

.c2 {
  grid-area: 1 / 2 / 2 / 3;
  border: 1px solid black;
  text-align: center;
}
<h1 >Big_Text</h1>
<p >Small_Text</p>

CodePudding user response:

Maybe add align-items:center to the parent element (which is body)

The align-items:center will remove whitespace so a solution isto padding to add whitespace

se padding to change the whitespace

<!DOCTYPE html>
<html>
    <head>
        <style>
            /* GRID AREA SYNTAX REFERENCE:
        grid-row-start, grid-column-start, grid-row-end, grid-column-end
        */
            body {
                display: grid;
                grid-template-columns: 1fr 1fr;
                grid-column-gap: 10px;
                /*Body Border Here for better visibility.*/
                border: 1px solid black;
                align-items:center;

            }
            .c1 {
                grid-area: 1 / 1 / 2 / 2;
                border: 1px solid black;
                text-align: center;
            }
            .c2 {
                padding:10px;
                grid-area: 1 / 2 / 2 / 3;
                border: 1px solid black;
                text-align: center;
     
            }
        </style>
    </head>
    <body>
        <h1 >Big_Text</h1>
        <p >all_Texmall_Texmall_Texmall_Tex</p>
    </body>
</html>

  • Related