【问题标题】:resizing background images with media queries to shrink with the browser window and stay center使用媒体查询调整背景图像的大小以随着浏览器窗口缩小并保持居中
【发布时间】:2018-07-11 08:23:27
【问题描述】:

我正在尝试构建一个使用带有 Bootstrap 4 的背景图像的网站。我希望图像调整大小,但不幸的是它会聚焦在图像上的不同点,因为它遇到断点而不是真正使图像居中。我应该通过 Photoshop 使用调整大小的图像还是通过 css 调整图像大小/缩小图像来调整图像大小。即我如何让背景图像保持在屏幕的中心。下面的媒体查询代码示例:(初始图像大小为 2000px x 1333px。谢谢!

.landpage-img {
    background: url(../img/bg-neon-01-2000x1333.jpg) no-repeat center center fixed;
}

【问题讨论】:

  • 试试 background-size:cover

标签: css twitter-bootstrap image background bootstrap-4


【解决方案1】:

您可以使用background-size: cover;background-size: contain;

像这样:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<style>
.landpage-img {
    background: url(https://picsum.photos/2000/1333) no-repeat center center fixed;
    background-size: cover;
}
</style>

<div class="container-fluid landpage-img" style="height: 100vh">
    <div class="row">
        <div class="col">
            Some content goes here
        </div>
    </div>
</div>

background-size: contain; 保持图像的比例,而background-size: cover; 旨在完全覆盖事物,即使图像需要稍微裁剪。因此,您可能大部分时间都想使用background-size: cover;

【讨论】:

    【解决方案2】:

    您可以进行父查询

    .parent {
    width: 100%;
    position:relative;
    }
    

    还有

    .landpage-img {
    position:absolute;
    left: 50%;
    transform: translateX(-50%);
    }
    

    并且您的图像将位于父选择器的中间。

    【讨论】:

      猜你喜欢
      • 2012-03-23
      • 1970-01-01
      • 2011-09-10
      • 2013-09-19
      • 2013-05-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多