代码之家  ›  专栏  ›  技术社区  ›  The Illusive Man

文本没有垂直居中

  •  0
  • The Illusive Man  · 技术社区  · 5 年前

    <!DOCTYPE html>
    <html>
        <head>
            <link rel="stylesheet" type="text/css" href="css.css">
        </head>
        <body id="background-image"
        style="background-image: url('background.jpg');" >
            <div class="container">
                wii jlkjkljkl fjkl jlkfsjlkfj klsajfkl sajkl jfklasj kfjsakl jlkfajs klfjlkasj fklasj klfjsakl lkfas
            </div>
        </body>
    </html>
    

    css.css的内容是:

    #background-image {
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
    }
    
    .container {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    

    我无法在屏幕中央显示文本。它水平居中,但不是垂直居中。也就是说,我看到一个背景图像,文本水平居中于图像顶部。我想把文字放在中间。

    发生了什么?我认为 flex align-items:center

    0 回复  |  直到 5 年前
        1
  •  2
  •   Lakshya Thakur    5 年前

    给予 body 高度 100vh container A. height 属于 100%

    为什么会这样?

    因为你的身体需要明确的高度来拉伸到100%的视口高度,而你的容器高度将是100%的视口高度,也就是100vh。现在,您的flex样式将按原样应用。

    早些时候,容器没有延伸到整个页面的高度。

    #background-image {
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
        height:100vh;
    }
    
    .container {
      display: flex;
      align-items: center;
      justify-content: center;
      height:100%;
    }
    
        2
  •  1
  •   Zerox92    5 年前

    你做得很完美,但你忘了一件小事。首先,您需要将#背景图像容器的高度设置为例如100vh。

    https://jsfiddle.net/dt5vxw6L/#&togetherjs=2DgR5IUFVN

    #background-image {
        background-repeat: no-repeat;
        background-attachment: fixed;
        background-size: cover;
        background-position: center center;
        background-color:red;
        display: flex;
        justify-content: center;
        align-items: center;
        **height: 100vh;**
    }
    
    .container {
      background-color:green;
      padding-top: auto;
      padding-bottom: auto;
    }