具有 CSS background 和 background-size 属性的解决方案

在下面的示例中,我们使用 <div> 元素并为其指定一个 class 属性,然后在 CSS 部分中设置该类的样式。
我们需要通过背景速记属性的“中心”值来指定图像的位置。
将图像的宽度设置为“100%”。
在这个例子中,我们还指定了图像的高度和背景大小。

使用 background 属性在 <div> 中居中背景图像的示例:

<!DOCTYPE html>
<html>
 <head>
   <title>文档的标题</title>
   <style>
     .bg-image {
       width: 100%;
       height: 200px;
       background: url("/bg.jpg") no-repeat center;
       background-size: 250px;
     }
   </style>
 </head>
 <body>
   <div class="bg-image"></div>
 </body>
</html>

如果我们想将背景图像置于 <div> 元素的中心并显示整个图像而不对其任何部分进行剪裁或者拉伸,请尝试以下示例,我们将 background-size 属性设置为其“包含”值。

使用 background-size 属性的“包含”值将背景图像居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .bg-image {
        height: 400px;
        background: url("/bg.jpg") no-repeat center;
        background-size: contain;
      }
    </style>
  </head>
  <body>
    <div class="bg-image"></div>
  </body>
</html>

我们的最后一个示例演示了如何使用背景图像填充整个 <div> 元素并且不留多余空间。
我们只需要使用 background-size 属性的“cover”值。

使用 background-size 属性的“cover”值将背景图像居中的示例:

<!DOCTYPE html>
<html>
  <head>
    <title>文档的标题</title>
    <style>
      .bg-image {
        width: 100%;
        height: 400px;
        background: url("/bg.jpg") no-repeat center;
        background-size: cover;
      }
    </style>
  </head>
  <body>
    <div class="bg-image">
      This is some example.
    </div>
  </body>
</html>
如何在 Div 中居中背景图像

在此代码中,我们将学习如何在 <div> 元素内将背景图像居中。

当然,我们需要 CSS 属性。

特别是,这可以借助 background 和 background-size 属性来实现。

我们可以在下面看到如何使用这些属性来实现我们的目标。

日期:2020-06-02 22:14:58 来源:oir作者:oir