0

I have this simple snippet:

<!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>

and the content of css.css is:

#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;
}

I can't display the text in the center of the screen. It's centered horizontally, but not vertically. That is, I see a background image with the text centered horizontally at the top of the image. And I want to have the text right in the center.

What's wrong? I thought the combination of flex and align-items:center was enough to make this happen.

2 Answers2

2

Give body a height of 100vh and container a height of 100% to achieve what you want.

Why so ?

Because your body needs that explicit height to stretch to 100% of the viewport height and your container height would be 100% of that which is again 100vh. Now your flex styling will apply as it should be.

Earlier the container was not stretching to the height of the whole page.

#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%;
}
Lakshya Thakur
  • 8,030
  • 1
  • 12
  • 39
1

You did it perfect, but you forgot one small thing. First you need to set the height of the #background-image container to for example 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;
}
Zerox92
  • 11
  • 1