页面中带有背景图像的中心 div

时间:2021-01-17 16:44:00

标签: html css flexbox

我想居中一个 div,它的内容在页面的中心。 div 有背景图片。

这是我对 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>

结果是这样的:
enter image description here

如您所见,内部文本显示在页面中央 - 这是我想要的,但我也希望背景图像也居中。

有什么建议吗?


更新:我尝试了一些建议,但这并没有达到预期的效果

with background-position: center;:这个看起来不错,只是只显示了图像的一部分。我希望图像缩放以适合父 div 的边界。 enter image description here

with background-size: cover:这本来是完美的,除了图像仍然没有居中。 enter image description here

2 个答案:

答案 0 :(得分:1)

您的 div 已经在中心。由于 div 的宽度大于图像,并且您使用了 background-size:contain,所以它没有出现应有的样子。

您可以使用:

background-position: center;

background-size:cover;

否则,您还可以减小内部 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>

答案 1 :(得分:0)

您可以使用 background-position: center; 属性将图像居中。

更新答案:

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

相关问题