Centering in CSS Grid

后端 未结 7 865
半阙折子戏
半阙折子戏 2020-11-21 07:11

I\'m trying to create a simple page with CSS Grid.

What I\'m failing to do is center the text from the HTML to the respective grid cells.

I\'ve tried placing

7条回答
  •  日久生厌
    2020-11-21 07:36

    You can use flexbox to center your text. By the way no need for extra containers because text is considered as anonymous flex item.

    From flexbox specs:

    Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item. However, an anonymous flex item that contains only white space (i.e. characters that can be affected by the white-space property) is not rendered (just as if it were display:none).

    So just make grid items as flex containers (display: flex), and add align-items: center and justify-content: center to center both vertically and horizontally.

    Also performed optimization of HTML and CSS:

    html,
    body {
      margin: 0;
      padding: 0;
    }
    
    .container {
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-rows: 100vh;
      
      font-family: Raleway;
      font-size: large;
    }
    
    .left_bg,
    .right_bg {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    
    .left_bg {
      background-color: #3498db;
    }
    
    .right_bg {
      background-color: #ecf0f1;
    }
    Review my stuff
    Hire me!

提交回复
热议问题