Center Text Vertically Within

后端 未结 7 2102
孤独总比滥情好
孤独总比滥情好 2020-12-05 16:57

I have a

element with a fixed height, and I\'d like to center some text vertically within that element.

I\'ve been trying to follow the inst

7条回答
  •  北海茫月
    2020-12-05 17:46

    I was recently delighted to find that Flexbox can handle this problem for you. The flex-center class in the CSS below will center your div's text, both vertically and horizontally. The example comes out a little smashed, so I recommend resizing the window until the div border isn't flush to the text.

    As far as whether you can get away with using flexbox regarding compatibility, see Can I use...

    I don't fully understand why this works, and if someone has more insight into the flex box machinery, I'd enjoy the explanation.

    .border-boxed {
      box-sizing: border-box;
    }
    
    *, *:before, *:after {
      box-sizing: inherit;
    }
    
    body {
      /* This is just to make it look pretty */
      box-sizing: border-box;
      background: linear-gradient(135deg, 
        rgba(85,239,203,1) 0%,
        rgba(30,87,153,1) 0%,
        rgba(85,239,203,1) 0%,
        rgba(91,202,255,1) 100%);
      color: #f7f7f7;
      font-family: 'Lato', sans-serif;
      font-weight: 300;
      font-size: .8rem;
      
      /* Expand  to entire viewport height */
      height: 100vh;
      
      /* Arrange the boxes in a centered, vertical column */
      display: flex;
      flex-direction: column;
      justify-content: center;
      align-items: center;
    }
    
    .flex-center {
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    
    .box {
      width: 25%;
      height: 25%;
      border: 2px solid #f7f7f7;
      border-radius: 16px;
      margin: .5rem; 
      text-transform: uppercase;
      text-align: center;
    }
    
    .small {
      height: 8%; 
    }
    Large Box.
    So big.
    My god.
    Smaller Box

提交回复
热议问题