html - 无法使具有固定高度和宽度响应的背景图像的 div

标签 html css sass pug

如您所见,当我最小化浏览器窗口时,我正在尝试使 container 成为响应式 background-image

我试过使用 max-widthpercentagesbackground-size:cover 和其他一些技巧,但他们没有不起作用,或者他们让我的容器消失了。

哈巴狗

section
  div(class='container')

SASS

section
  height: 100vh
  width: 100vw
  background: gray
  .container
    position: absolute
    background: url('https://www.triplejtours.com.au/wp-content/uploads/2016/02/Lake-Kununurra-reflections-Dylan-Lodge.jpg')
    background-repeat: no-repeat
    background-position: center
    background-size: cover
    height: 807px
    width: 948px
    left: 50%
    top: 50%
    transform: translate(-50%,-50%)

CodePen

最佳答案

你可以尝试这样的事情:

body {
  margin: 0;
}

.container {
  height: 100vh;
  width: 100vw;
  display: flex; /*use flex to easily center*/
  background: gray;
}

.container>div {
  background: url('https://www.triplejtours.com.au/wp-content/uploads/2016/02/Lake-Kununurra-reflections-Dylan-Lodge.jpg');
  background-repeat: no-repeat;
  background-position: center; /*keep it center within the centred div*/
  background-size: contain; /*use contain to make the image shrink visually*/
  width: 100%;
  height: 100%;
  margin: auto; /*center the div*/
  max-width: 948px; /*Image width*/
  max-height: 807px; /*Image height*/
}
<div class="container">
  <div></div>
</div>

关于html - 无法使具有固定高度和宽度响应的背景图像的 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51050709/

相关文章:

html - 当我放大页面时,如何使页面的滚动条出现?

javascript - 使用 AJAX 重新加载 div 后无法选择 Jquery 元素

css - Chrome 自动填充黄色背景位于表单字段中的图标上方

css - 步骤指示器 CSS

javascript - 如何检查元素是否具有某种样式以及它是否具有样式更改另一个元素的样式?

html - 如何在 html/css 中用图像替换文本

javascript - 在 bootstrap 3 中单击更改列宽

ruby-on-rails - 如何为 rails 5.2 安装本地字体

css - Angular 6sass 全局变量

html - 如何等待 HTML 中的视频背景直到它完成然后查看正文部分的内容?