【问题标题】:Trouble making a div with a background-image with fixed height and width responsive无法使具有固定高度和宽度的背景图像的 div 响应
【发布时间】:2018-06-26 20:12:28
【问题描述】:

如您所见,当我最小化浏览器窗口时,我正试图让 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

【问题讨论】:

  • 固定高度/宽度和响应?你能详细说明一下吗?
  • 我使用的图像的高度为 807 像素,宽度为 948 像素。所以容器也应该有那个尺寸。我知道我的前提是糟糕和模糊的。有什么办法可以让这个容器响应吗?
  • 您希望响应式如何表现?
  • 当我最小化浏览器窗口时,我希望它同时缩小。

标签: html css sass pug


【解决方案1】:

你可以试试这样的:

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>

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2014-11-25
    • 2013-10-24
    • 1970-01-01
    • 2014-05-29
    • 1970-01-01
    • 2013-12-09
    • 1970-01-01
    相关资源
    最近更新 更多