Your div is already in the center. Since the width of div is larger than image and you used background-size:contain, so it’s not appearing as it should be.
You can use:
background-position: center;
or
background-size:cover;
Else you can also reduce the width of your inner div.
<html>
<head>
<style>
.flex_container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.inner {
height:300px;
width: 400px;
background-image: url('https://effortcatalyst.online/matrix_bg.png');
background-size: cover;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="flex_container">
<div class="inner">
<h1> Some text in the center </h1>
</div>
</div>
</body>
</html>
You could use background-position: center;
property to center the image.
Updated Answer:
<html>
<head>
<style>
.flex_container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.inner {
height: 100vh;
width: 100vw;
background-image: url('https://effortcatalyst.online/matrix_bg.png');
background-size: cover;
color: white;
display: flex;
justify-content: center;
align-items: center;
}
</style>
</head>
<body>
<div class="flex_container">
<div class="inner">
<h1> Some text in the center </h1>
</div>
</div>
</body>
</html>
I want to center a div, and it’s content in the center of the page. The div has a background image.
This is my attempt with Flexbox
:
<head>
<style>
.flex_container {
display: flex;
flex-direction: row;
justify-content: center;
align-items: center;
}
.inner {
height: 788px;
width: 1400px;
background-image: url('matrix_bg.png');
background-size: contain;
background-repeat: no-repeat;
color: white;
display: flex;
justify-content: center;
}
</style>
</head>
<div class="flex_container">
<div class="inner">
<div style="margin-top: 100px;"> Some text in the center </div>
</div>
</div>
And the result is like this:

As you can see, the inner text appears centered in the page – this is what I want, but I also would want the background image also to be centered.
Any suggestions?
Update: I tried a few suggestions, but this does not give the desired effect:
with background-position: center;
: this one seems fine, except only a portion of the image is shown. I would like the image to scale to fit within the bounds of the parent div
.

with background-size: cover
: this would have been perfect, except the image is still not centered.

See my updated answer, I tried your suggestion but this still does not give the desired result.
Try running the above code snippet. This time I’ve used an image.
See my updated answer, I tried your suggestion but this still does not give the desired result.
The issue is that your div is taking only the space which you set for .inner class. I have updated my answer in which I used 100vh and 100vw for full height and width, like you wanted